运算符重载(operator overloading)
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
在C++中,可以定义一个处理类的新运算符。这种定义很像一个普通的函数定义,只是函数的名字由关键字 operator 及其紧跟的运算符组成,差别仅此而已。它像任何其他函数一样也是一个函数,当编译器遇到适当的模式时,就会调用这个函数。
1. 加号运算符重载
如果想让自定义数据类型 进行+运算 需要重载 + 运算符
在成员函数 或 全局函数 里重写一个 + 运算符的函数
函数名 operator+(){}
运算符重载 也可以提供多个版本
class Person9 {
public:
Person9() {};
Person9(int a, int b) :m_A(a), m_B(b) {};
//"+"号运算符重载,成员函数
Person9 operator+(Person9& p) {
Person9 tmp;
tmp.m_A = this->m_A + p.m_A;
tmp.m_B = this->m_B + p.m_B;
return tmp;
}
Person9 operator+(int a) {
Person9 tmp;
tmp.m_A = this->m_A + a;
tmp.m_B = this->m_B + a;
return tmp;
}
int m_A;
int m_B;
};
//利用全局函数 进行"+"号运算符重载
Person9 operator+(Person9& p1, Person9& p2) {
Person9 tmp;
tmp.m_A = p1.m_A + p2.m_A;
tmp.m_B = p1.m_B + p2.m_B;
return tmp;
}
void test9() {
Person9 p1(1, 2);
Person9 p2(3, 4);
Person9 p3 = p1 + p2;
cout << "p3's m_A:" << p3.m_A << " ; ";
cout << "p3's m_B:" << p3.m_B << endl;
Person9 p4 = p3 + 1;
cout << "p4's m_A:" << p4.m_A << " ; ";
cout << "p4's m_B:" << p4.m_B << endl;
}
对于内置数据类型的表达式的运算符是不可能改变的。
2. 左移运算符重载
重载左移运算符不可以写到成员函数中
不要随意乱用符号重载
内置数据类型 的运算符不可以重载
cout<<直接对 Person 自定义数据类型 进行输出
写到 全局函数中 ostream& operator<<(ostream& cout, Person& p){};
如果重载的时候想访问 p1 的私有成员, 那么全局函数要做 Person 的友元函数
class Person09 {
friend ostream& operator<<(ostream& cout, Person09& p);
public:
Person09() {};
Person09(int a, int b) {
this->m_A = a;
this->m_B = b;
}
private:
int m_A;
int m_B;
};
ostream& operator<<(ostream& cout, Person09& p) {
cout << "m_A = " << p.m_A << endl;
cout