使用成员函数重载复数类的运算符+
时间: 2023-09-17 16:09:14 浏览: 45
以下是复数类的成员函数重载运算符的示例:
```c++
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex operator*(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex operator/(const Complex& c) const {
double r = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / r, (imag * c.real - real * c.imag) / r);
}
Complex operator+=(const Complex& c) {
real += c.real;
imag += c.imag;
return *this;
}
Complex operator-=(const Complex& c) {
real -= c.real;
imag -= c.imag;
return *this;
}
Complex operator*=(const Complex& c) {
double r = real * c.real - imag * c.imag;
double i = real * c.imag + imag * c.real;
real = r;
imag = i;
return *this;
}
Complex operator/=(const Complex& c) {
double r = c.real * c.real + c.imag * c.imag;
double nreal = (real * c.real + imag * c.imag) / r;
double nimag = (imag * c.real - real * c.imag) / r;
real = nreal;
imag = nimag;
return *this;
}
bool operator==(const Complex& c) const {
return real == c.real && imag == c.imag;
}
bool operator!=(const Complex& c) const {
return !(*this == c);
}
};
```
这个示例中,复数类有四个基本的运算符:加、减、乘、除。每个运算符都返回一个新的复数对象,而不是修改当前对象。此外,还有四个复合赋值运算符(+=、-=、*=、/=),它们修改当前对象并返回它。最后,还有两个比较运算符(== 和 !=),它们比较两个复数对象的实部和虚部是否相等。