C++:运算符重载与类的赋值运算符重载函数

简介: C++:运算符重载与类的赋值运算符重载函数

章节知识架构

一.运算符重载

  1. 运算符重载的基本概念

    代码段1

2.关于运算符重载的重要语法细则

二.运算符重载在类中的使用

三.类的默认成员函数:=重载函数(赋值运算符重载)

1.自定义=重载函数

代码段2

2.编译器默认生成的=重载函数

四.前置++(--)和后置++(--)的重载

章节知识架构

一.运算符重载
C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数

  1. 运算符重载的基本概念

C++中定义运算符重载的关键字:operator

运算符重载本质上是函数,具有返回值类型,函数名字以及参数列表,其返回值类型和参数列表与普通的函数定义规则类似;
运算符重载函数的函数名命名规则:关键字operator + 需要重载的运算符符号(例如定义函数名operator>,表示>的运算符重载);
运算符重载函数的形参个数必须和被重载运算符的目数相同:单目操作符的重载函数有且只有一个形参,双目操作符的重载函数有且只有两个形参.
运算符重载函数必须有一个类类型参数
运算符重载函数首部的一般形式:返回值类型+operator运算符+(参数列表);
比如:

现在有一个记录日期的类Date,我们想比较两个日期类对象所记录的日期大小,因此设计一个运算符 '>'的重载函数。

函数返回类型定义为bool;bool为一个字节的整形,其只能为true(值1)或false(值为0)

函数名定义为: operator>

函数的形参表为:(const Date & date2 ,const Date & date2)

代码段1

include

using std::cout;
using std::cin;
using std::endl;

class Date 记录日期的类
{
public:

Date(int day = 0, int month = 0,int year = 0)          Date的带参构造函数
{
    _day = day;
    _month = month;
    _year = year;
}

int _day;
int _month;
int _year;
AI 代码解读

};

bool operator> (const Date& date1, const Date& date2) 将 > 运算符进行重载用于日期比较
{

if (date1._year > date2._year)
{
    return true;
}
else if (date1._year == date2._year && date1._month > date2._month)
{
    return true;
}
else if (date1._year == date2._year && date1._month == date2._month && date1._day >                 
date1._day)
{
    return true;
}
return false;
AI 代码解读

}

int main()
{

Date a(2021, 4, 23);
Date b(2022, 1, 27);

if (a > b)                      用运算符重载来比较两个日期对象
{
    cout << "Date a > Date b" << endl;
}
else
{
    cout << "Date a < Date b" << endl;
}
return 0;
AI 代码解读

}

C++编译其会根据运算符的操作数的类型来判断该运算符是否要调用重载以及调用哪种形式的重载,比如上述代码段主函数中的 a>b表达式:

2.关于运算符重载的重要语法细则
不能通过连接其他符号来创建新的操作符:比如operator@
作为类成员运算符重载函数时,其形参个数看起来比运算符目数少1,因为类成员函数的第一个参数为隐藏的this指针;关于this指针:http://t.csdn.cn/hncvq
赋值运算符重载(比如=,+=,-+,*=等等)只能作为类的成员函数不能重载成全局函数
'".* " "::" "sizeof" "?:" "." 注意以上5个运算符不能重载。
二.运算符重载在类中的使用
C++引入运算符重载是为了提高代码的可读性,允许我们构建复杂类对象之间的运算表达式。
运算符重载必须有一个类类型形参,因此在运算符重载函数中我们难免要访问类的成员变量
为了保证封装性,类的成员变量往往定义在类的私有域中。
所以为了保证类对象的封装性的同时可以让运算符重载函数直接访问到类的成员变量,大多数情况下我们往往把运算符重载函数定义为类的成员函数(方法)。
现在对代码段1进行优化:

把运算符重载函数定义为类的成员函数(方法)

运算符重载函数定义为类的成员函数时注意不要忽略this指针

include

using std::cout;
using std::cin;
using std::endl;

class Date //记录日期的类
{
public:

Date(int day = 0, int month = 0,int year = 0)
{
    _day = day;
    _month = month;
    _year = year;
}

bool operator> (const Date& date)       //将 > 运算符进行重载
{
    if (_year > date._year)
    {
        return true;
    }
    else if (_year == date._year &&_month > date._month)
    {
        return true;
    }
    else if (_year == date._year && _month == date._month && _day > date._day)
    {
        return true;
    }
    return false;
}
AI 代码解读

private:

int _day;
int _month;
int _year;
AI 代码解读

};

int main()
{

Date a(29, 4, 2020);
Date b(27, 4, 2020);

if (a > b)
{
    cout << "Date a > Date b" << endl;
}
else
{
    cout << "Date a < Date b" << endl;
}
return 0;
AI 代码解读

}

简单地观察一下 a>b表达式的汇编指令:

三.类的默认成员函数:=重载函数(赋值运算符重载)
类的默认成员函数中有一个赋值运算符=的重载:

如果我们没有在类中自定义一个赋值运算符=的重载,编译器会在类中自动生成一个默认的=运算符重载函数。

1.自定义=重载函数
赋值运算符(=)只能重载成类的成员函数不能重载成全局函数

原因:赋值运算符如果没有被我们定义,编译器会在类中(任何类中)生成一个默认的赋值运算符重载。此时若我们在类域外定义一个全局的赋值运算符重载,就会和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
自定义=重载函数:

现在Date类中实现一个=重载函数:如果我们在类中自定义了=重载函数,编译器便不会在编译阶段自动生成其默认的赋值运算符(=)重载。

代码段2
using std::cout;
using std::cin;
using std::endl;

class Date 记录日期的类
{
public:

Date(int day = 0, int month = 0,int year = 0)
{
    _day = day;
    _month = month;
    _year = year;
}

bool operator> (const Date& date)       将 > 运算符进行重载
{
    if (_year > date._year)
    {
        return true;
    }
    else if (_year == date._year &&_month > date._month)
    {
        return true;
    }
    else if (_year == date._year && _month == date._month && _day > date._day)
    {
        return true;
    }
    return false;
}

Date& operator=(const Date& date)        将 = 运算符进行重载
{
    _day = date._day;
    _month = date._month;
    _year = date._year;
    return (*this);
}
AI 代码解读

private:

int _day;
int _month;
int _year;
AI 代码解读

};

int main()
{

Date a(29, 4, 2020);
Date b;
Date c;

c = b = a;                              用=的重载完成连续赋值

if (a > b)
{
    cout << "Date a > Date b" << endl;
}
else 
{
    cout << "Date a <= Date b" << endl;
}
return 0;
AI 代码解读

}

可以试着观察一下代码段中c=b=a的汇编指令:

注意:=重载函数使用引用传参和引用返回而不使用值传参和值返回是为了提高代码的运行效率(值传递需要拷贝出临时的类对象)

参见:http://t.csdn.cn/Rc5aI

       http://t.csdn.cn/9tLyK
AI 代码解读

2.编译器默认生成的=重载函数
编译器默认生成的=重载函数:

编译器默认生成的=运算符重载函数的功能和代码段2中自定义的=重载函数功能类似:

可以简单验证一下:

将代码段2中等号重载的代码段注释掉

using std::cout;
using std::cin;
using std::endl;

class Date //记录日期的类
{
public:

Date(int day = 0, int month = 0,int year = 0)
{
    _day = day;
    _month = month;
    _year = year;
}

bool operator> (const Date& date)       //将 > 运算符进行重载
{
    if (_year > date._year)
    {
        return true;
    }
    else if (_year == date._year &&_month > date._month)
    {
        return true;
    }
    else if (_year == date._year && _month == date._month && _day > date._day)
    {
        return true;
    }
    return false;
}

//Date& operator=(const Date& date)     //将等号重载的代码段注释掉
//{
//    if (this != &date)
//    {
//        _day = date._day;
//        _month = date._month;
//        _year = date._year;
//    }

//    return (*this);
//}
AI 代码解读

private:

int _day;
int _month;
int _year;
AI 代码解读

};

int main()
{

Date a(29, 4, 2020);
Date b;
Date c;

c = b = a;

if (a > b)
{
    cout << "Date a > Date b" << endl;
}
else 
{
    cout << "Date a <= Date b" << endl;
}
return 0;
AI 代码解读

}

如果,类中有类对象成员变量,该类的编译器默认生成的=重载函数中会去调用其成员类对象的赋值运算符重载。

比如:

using std::cout;
using std::cin;
using std::endl;

class subclass //定义一个被嵌套的类
{
public:

subclass(int a = 100)             定义subclass的构造函数
{
    _a = 100;
}
subclass& operator = (const subclass& date)       定义subclass的赋值运算符重载函数
{
    _a = date._a;
    cout << "hello" << endl;                      打印一下表示该函数被调用
    return (*this);
}
AI 代码解读

private:

int _a;
AI 代码解读

};

class Date //记录日期的类
{
public:

Date(int day = 0, int month = 0,int year = 0,int subclass=0)
{
    _day = day;
    _month = month;
    _year = year;
}

//bool operator> (const Date& date)       //将 > 运算符进行重载
//{
//    if (_year > date._year)
//    {
//        return true;
//    }
//    else if (_year == date._year &&_month > date._month)
//    {
//        return true;
//    }
//    else if (_year == date._year && _month == date._month && _day > date._day)
//    {
//        return true;
//    }
//    return false;
//}

//Date& operator=(const Date& date)     //将等号重载的代码段注释掉
//{
//    if (this != &date)
//    {
//        _day = date._day;
//        _month = date._month;
//        _year = date._year;
//    }

//    return (*this);
//}
AI 代码解读

private:

int _day;
int _month;
int _year;
subclass _subdate;
AI 代码解读

};

int main()
{

Date a(29, 4, 2020,100);
Date b;
Date c;

c = b = a;

//if (a > b)
//{
//    cout << "Date a > Date b" << endl;
//}
//else 
//{
//    cout << "Date a <= Date b" << endl;
//}
return 0;
AI 代码解读

}

可以通过汇编指令来观察这个过程:

需要注意的是:类似于拷贝构造函数,编译器在类中默认生成的赋值运算符重载是以逐个字节进行拷贝的方式完成类对象赋值的(这种拷贝方式称为浅拷贝)。
因此编译器默认生成的赋值运算符重载不能用于一些申请了额外内存资源类对象之间的拷贝赋值。(比如栈对象之间的拷贝赋值)
如果栈对象之间使用编译器默认生成的=重载函数,则会出现以下情形:

所以涉及到内存资源管理的类对象之间只能使用用户自定义的=重载完成深拷贝。

四.前置++(--)和后置++(--)的重载
针对Date类,我们来实现一下表示日期自增的++重载(日期增加一天)

using std::cout;
using std::cin;
using std::endl;

//class subclass //定义一个被嵌套的类
//{
//public:
// subclass(int a = 100) //定义subclass的构造函数
// {
// _a = 100;
// }
// subclass& operator = (const subclass& date) //定义subclass的赋值运算符重载函数
// {
// _a = date._a;
// cout << "hello" << endl; //打印一下表示该函数被调用
// return (*this);
// }
//private:
//
// int _a;
//};

class Date //记录日期的类
{
public:

Date(int day = 0, int month = 0, int year = 0)   //Date的构造函数
{
    _day = day;
    _month = month;
    _year = year;
}

//bool operator> (const Date& date)       //将 > 运算符进行重载
//{
//    if (_year > date._year)
//    {
//        return true;
//    }
//    else if (_year == date._year &&_month > date._month)
//    {
//        return true;
//    }
//    else if (_year == date._year && _month == date._month && _day > date._day)
//    {
//        return true;
//    }
//    return false;
//}

//Date& operator=(const Date& date)     
//{
//    if (this != &date)
//    {
//        _day = date._day;
//        _month = date._month;
//        _year = date._year;
//    }

//    return (*this);
//}
Date& operator++()             //实现日期类的前置++
{
    _day++;
    return (*this);
}

Date operator++(int)           //实现日期类的后置++
{
    Date tem(*this);
    _day++;
    return tem;
}

void Print()                    //类对象的日期打印函数
{
    cout << _year << ' ' << _month << ' ' << _day << ' ' << endl;
}
AI 代码解读

private:

int _day;
int _month;
int _year;
AI 代码解读

};

int main()
{

Date a(5, 4, 2020);
a.Print();
Date ret1(a++);
ret1.Print();
Date ret2(++a);
ret2.Print();
return 0;
AI 代码解读

}

代码图解:

注意一个语法细则:

前置--和后置--的重载和++类似。

目录
打赏
0
0
0
0
18
分享
相关文章
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
46 0
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
116 0
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
115 12
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
101 16
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
4月前
|
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
237 6