标签:lis int sizeof mes pre 优先 plain out 一个
运算符重载的本质也是对已有功能的扩展
运算符重载的本质就是函数重载,只是函数变成了 operator + 运算符
当成员函数和全局函数对运算符进行重载时,优先调用成员函数
运算符重载为成员函数时,可以少一个参数,调用时,以右参数为参数进行函数调用
不可以重载的运算符: . :: sizeof ?:
运算符重载不改变参数个数,优先级,结合性
例子
1 #include <iostream> 2 3 using namespace std; 4 5 class Test 6 { 7 private: 8 int a; 9 10 public: 11 Test() {a = 0;} 12 13 Test(int a) {this->a = a;} 14 15 void show() 16 { 17 cout << "a = " << a << endl; 18 } 19 20 Test operator + (Test& t) 21 { 22 Test rtn(0); 23 rtn.a = this->a + t.a; 24 return rtn; 25 } 26 }; 27 28 int main() 29 { 30 Test t, t1(1), t2(2); 31 t = t1.operator + (t2); //等同于 t = t1 + t2; 32 t.show(); 33 return 0; 34 }
1 #include <iostream> 2 3 using namespace std; 4 5 class Test 6 { 7 private: 8 int a; 9 10 public: 11 Test() {a = 0;} 12 13 Test(int a) {this->a = a;} 14 15 int getA() {return a;} 16 17 void setA(int a) {this->a = a;} 18 19 void show() 20 { 21 cout << "a = " << a << endl; 22 } 23 }; 24 25 Test operator + (Test& t1, Test& t2) 26 { 27 Test rtn(0); 28 rtn.setA(t1.getA() + t2.getA()); 29 return rtn; 30 } 31 32 int main() 33 { 34 Test t, t1(1), t2(2); 35 t = t1 + t2; 36 t.show(); 37 return 0; 38 }
标签:lis int sizeof mes pre 优先 plain out 一个
原文地址:https://www.cnblogs.com/chusiyong/p/11294634.html