运算符的重载
C++通过运算符重载的操作赋予了运算符新的功能,使得预定义的运算符可以对我们自己定义的数据类型进行操作,扩展了运算符的功能
#include <iostream>
using namespace std;
//定义com类,该类有两个成员real 和 img,重载运算符“+”
class com
{
private:
int real, img;
public:
com(int real = 0, int img = 0)
{
this->real = real;
this->img = img;
}
//函数参数比原来的操作数少一个是因为:
//this指针隐式的访问了类的一个对象,它充当了运算符函数最左边的操作数
com operator + (com x)//当 com类 + com类时,执行(x1,y1) = (x1+x2,y1+y2)
{
return com(this->real + x.real, this->img + x.img);
}
com operator + (int x)//当 com类 + int数值时,执行(x1,y1) = (x1+x,y1)
{
return com(this->real + x, this->img);
}
//友元函数没有this指针,因此操作数的个数没有变化
//所有的操作数都必须通过函数的形参进行传递,函数的参数与操作数自左至右一一对应
friend com operator + (int x, com y)//当 int数值 +com类时,执行(x1,y1) = (x+x1,y1)
{
return com(x + y.real, y.img);
}
void show()
{
cout << real << "," << img << endl;
}
};
int main()
{
com a;
com b(10, 10);
com c(100, 100);
a = b + c;// com类 + com类
a.show();
a = b + 1;// com类 + int数值
a.show();
a = 1 + c;// int数值 + com类
a.show();
system("pause");
return 0;
}
转载自:黑凤梨の博客