1.从函数重载说起
-> 函数重载是在一定作用域内,多个函数名相同但参数列表不同的函数重载。
-> 编译时由编译器根据实际调用时给的实参情况来判定本次实际用哪个函数,这个过程叫重载决策。
2.运算符重载
譬如+ - * / %
等算术运算符和> < == !=
等关系运算符就是典型的可重载运算符(但不是所有的运算符都可以重载,譬如sizeof)。
编译器为每个类默认重载了赋值操作符。
代码示例:
#include <iostream>
using namespace std;
class coordinate
{
public:
int x;
int y;
coordinate();
coordinate(int x0,int y0);
void print(void);
//定义类的时候,提供一个运算符重载的对应解析函数即可
//返回值 函数名 参数列表
coordinate operator+ (const coordinate other);
};
//默认构造函数
coordinate::coordinate()
{
x = 0;
y = 0;
}
//带参数构造函数
coordinate::coordinate(int x0,int y0)
{
x = x0;
y = y0;
}
//打印坐标函数
void coordinate::print(void)
{
cout << "(" << this->x <<","<< this->y << ")" <<endl;
}
//运算符重载"+"解析函数
coordinate coordinate::operator+ (const coordinate other)
{
//在该函数内,去实现"+"的真正应该做的操作
coordinate tmp;
tmp.x = this->x + other.x;
tmp.y = this->y + other.y;
return tmp;
}
int main()
{
coordinate a(1,3);
coordinate b(2,5);
coordinate c;
c = a+b; //被编译器翻译成: c = a.operator+(b);
c.print(); // 成功打印 (3,8)
return 0;
}
3.运算符重载的本质
-> 表面上,运算符重载是对C++源生运算符的意义,在某个class中做重定义。
-> 本质上,运算符被映射到执行相应的成员函数,所以运算符重载其实是重定义对象的运算符所对应的函数。
4.运算符重载的意义
-> 运算符重载是一种语法特性,C++全面支持,Java不支持,python有限度的支持。
-> 没有运算符重载照样写代码,所有操作全部通过显式调用相应成员函数来完成即可。
-> 运算符重载一定程度上体现了C++的多态性,因为同样的运算符在不同的class中表现是不同的。
5.运算符+的重载中的对应关系回顾
coordinate coordinate::operator+ (const coordinate other)
{
//在该函数内,去实现"+"的真正应该做的操作
coordinate tmp;
tmp.x = this->x + other.x;
tmp.y = this->y + other.y;
return tmp;
}
总结:a + b; 等价于 a.operator+(b)
,a对应this,b对应函数参数other,a+b的表达式的值对应函数返回值。
6.运算符=的重载中的对应关系
//运算符重载"="解析函数1_2
void coordinate::operator=(const coordinate other)
{
//在该函数内,去实现"="的真正应该做的操作
//c = a; c是this,a是other,c=a整个表达式的值是返回值
this->x = other.x;
this->y = other.y;
return ; //实现为无返回值的函数时,在对对象进行 = 的时候不能连等,也就是说不支持 d = (c = a) ;
}
coordinate coordinate::operator=(const coordinate other)
{
//在该函数内,去实现"="的真正应该做的操作
//c = a; c是this,a是other,c=a整个表达式的值是返回值
this->x = other.x;
this->y = other.y;
return *this; //实现为有返回值的函数时可以支持 d = (c = a) ;这样连等的形式
}
总结:c = a; 等价于 c.operator=(a);
c对应this,a对应other,c=a整个表达式的值(其实就是c)对应函数返回值。
7.运算符+=的重载中的对应关系
//运算符重载"+="解析函数
void coordinate::operator+=(const coordinate other)
{
//a += b; 效果上等价于 a = a + b;
// c = (a += b); 我们一般不会这样写,所以定义成无返回值就行
//a是this ,b是other ,操作完成a 的值改变,b的值不改变
this->x = this->x + other.x;
this->y = this->y + other.y;
return;
}
总结:a += b; 等价于 a.operator+=(b);
a对应this,b对应other,a+=b的整体表达式对应返回值。