双目运算符的重载

http://blog.csdn.net/cyp331203/article/details/23954369

 实际上,在运算符重载中,友元函数运算符重载函数与成员运算符重载函数的区别是:友元函数没有this指针,而成员函数有,因此,在两个操作数的重载中友元函数有两 个参数,而成员函数只有一个。当重载为成员函数时,左操作数由this指针传递,右操作数由参数ObjectR传递.重载为友员函数时,左右操作数都由参数传递。且不能用友元函数重载的符号有:“=,(),[],->”记住,成员函数必须是符号的左操作数。

        对于单目运算符,通常用成员函数,来的简便

        双目运算符,通常用友元函数,没有操作数左右的限制

        对于运算符” =,(),[],->”只能作为成员函数。


于是做修改如下:


 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class integer{
 5     public:
 6         integer(int value=0):value(value){}
 7         /*integer operator+(integer itg) {
 8             //return value+=itg.value;//i=2,ii=2
        return itg.value+=value;//i=0,ii=2
9 }*/ 10 friend integer operator+(const integer& a,const integer& b){//为何是const类型? 11 return a.value+b.value; 12 } 13 friend ostream& operator<<(ostream& os,const integer& it){ 14 return os << it.value; 15 } 16 private: 17 int value; 18 }; 19 20 int main() 21 { 22 integer i; 23 cout << "初始值i=" << i << endl; 24 integer ii; 25 ii = i+2; 26 ii = 2+i; 27 cout << "相加之后i=" << i << endl; 28 cout << "ii=" << ii << endl; 29 return 0; 30 }

 

C++运算符重载时参数什么时候要加&?什么时候要加const?

【不太成熟的参考】为什么重载运算符的函数要用const   C++ 重载运算符 成员 友元 const

 

原文地址:https://www.cnblogs.com/guxuanqing/p/5933895.html