#include<iostream>
using namespace std;
class complex {
public:
double real;
double imag;
complex(double r = 0, double i = 0)
{
real = r; imag = i;
}
};
complex operator+(complex co1, complex co2)
{
complex temp;
temp.real = co1.real * co2.real-co1.imag* co2.imag;
temp.imag = co1.imag * co2.real + co1.real * co2.imag;
return temp;
}
int main()
{
complex com1(1.0, 2.0), com2(3.0, 4.0), total1, total2;
total1 = operator+(com1, com2);
cout << "real1=" << total1.real << "" << "imag1 = " << total1.imag << endl;
/*total2 = com1 + com2;
cout << "real2=" << total2.real << "" << "imag2= " << total2.imag << endl;*/
return 0;
}
本次上机需要利用运算符的重载实现两个复数相加。C ++ 中预定义的运算符的操作对象只能是基本数据类型。但实际上,对于许多用户自定义类型(例如类),也需要类似的运算操作。这时就必须在C ++ 中重新定义这些运算符,赋予已有运算符新的功能,使它能够用于特定类型执行特定的操作,这就是运算符的重载。运算符重载的实质是函数重载,它提供了C ++ 的可扩展性,也是C ++ 最吸引人的特性之一。但并不是所有的运算符都可以重载,比如成员访问运算符(.)、成员指针访问运算符(.*)、作用域运算符(::)、长度运算符(sizeof)、条件运算符(?:),再就是c++只能不能对用户自定义的新的运算符进行重载,因此运算符的重载给我的第一印象就是非常的“人性化”,但在上机过程中我更改了+为*之后,结果还是对的,但这样可能会导致违背运算符重载的初衷,导致程序可读性大大减弱,造成混乱。