使用友元函数进行加号和逗号的运算符重载。注意友元函数并不是成员函数。
#include<iostream>
#include<malloc.h>
using namespace std;
class Rect
{
public:
int x,y;
Rect()
{};
Rect(int l,int w)
{
x = l;y = w;
}
void disp()
{
cout<<"面积: "<<x*y<<endl;
}
friend Rect operator,**(Rect w,Rect r**)
{
Rect temp;
temp.x = r.x;
temp.y = r.y;
return temp;
}
friend Rect operator+(**Rect r1,Rect r2**)
{
Rect temp;
temp.x = r1.x + r2.x;
temp.y = r1.y + r2.y ;
return temp;
}
};
int main()
{
Rect r1(1,2);
cout<<"矩阵1的面积是:";
r1.disp();
Rect r2(3,4);
cout<<"矩阵2的面积是: ";
r2.disp();
Rect r3(5,6);
cout<<"矩阵3的面积是:";
r3.disp();
cout<<"调用逗号运算符"<<endl;
r1 = (r1,r2+r3);
cout<<"矩阵1的面积是:";
r1.disp();
r1 = (r1,r2+r3,r3);
cout<<"矩阵1的面积是: ";
r1.disp();
return 0;
}
如果不使用友元函数,而使用一般的成员函数来重载逗号运算符,则只带一个右运算符,而左运算符由指针this提供。
#include<iostream>
#include<malloc.h>
using namespace std;
class Rect
{
public:
int x,y;
Rect()
{};
Rect(int l,int w)
{
x = l;y = w;
}
void disp()
{
cout<<"面积: "<<x*y<<endl;
}
Rect operator,(Rect r)
{
Rect temp;
temp.x = r.x;
temp.y = r.y;
return temp;
}
Rect operator+(Rect r)
{
Rect temp;
temp.x = r.x + x;
temp.y = r.y +y ;
return temp;
}
};
int main()
{
Rect r1(1,2);
cout<<"矩阵1的面积是:";
r1.disp();
Rect r2(3,4);
cout<<"矩阵2的面积是: ";
r2.disp();
Rect r3(5,6);
cout<<"矩阵3的面积是:";
r3.disp();
cout<<"调用逗号运算符"<<endl;
r1 = (r1,r2+r3);
cout<<"矩阵1的面积是:";
r1.disp();
r1 = (r1,r2+r3,r3);
cout<<"矩阵1的面积是: ";
r1.disp();
return 0;
}