#include<iostream>
using namespace std;
#include<math.h>
class complex {
float real, image;
public:
complex(float r = 0, float i = 0)
{
real = r; image = i;
}
complex & operator+=(complex b)
{
real += b.real;
image += b.image;
return *this;
}
complex operator*=(complex b)
{
real += b.real;
image += b.image;
return *this;
}
void display()
{
cout << real << (image >= 0 ? '+' : '-') << "j*" << fabs(image) << endl;
}
};
int main() { return 0; }
你能告诉我复数运算符*=(复数b)的区别吗 和复数 & operator+=(复数 b)
非常感谢!
最佳答案
operator*=
的实现不正确。它与 operator+=
的作用相同。此外,它返回一个拷贝而不是一个引用。
更好的实现方式是:
complex& operator*=(complex b)
{
double tempReal = real*b.real - image*b.image;
double tempImage = real*b.image + image*b.real;
real = tempReal;
image = tempImage;
return *this;
}
关于c++ - 2 运算符重载有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612541/