完整定义复数类Complex,在其中重载常见运算符,如“+”“-”“++”“--”“+=”,并且重载“==”和“!=”,使之能够比较两个复数
时间: 2023-11-02 17:05:19 浏览: 281
实验五、运算符重载 复数+-*/ 大数+-*/
好的,我理解了你的问题。以下是Complex类的定义,其中重载了常见的运算符和比较运算符:
```C++
#include<iostream>
using namespace std;
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 den = c.real*c.real + c.imag*c.imag;
return Complex((real*c.real+imag*c.imag)/den, (imag*c.real-real*c.imag)/den);
}
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 den = c.real*c.real + c.imag*c.imag;
double r = (real*c.real + imag*c.imag)/den;
double i = (imag*c.real - real*c.imag)/den;
real = r;
imag = i;
return *this;
}
bool operator==(const Complex& c) const {
return (real==c.real) && (imag==c.imag);
}
bool operator!=(const Complex& c) const {
return !(*this == c);
}
friend ostream& operator<<(ostream& os, const Complex& c);
};
ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << "," << c.imag << ")";
return os;
}
```
在这个类中,我们定义了构造函数,以便我们可以使用默认参数或传递实部和虚部来创建Complex对象。
我们重载了加、减、乘、除、+=、-=、*=、/= 运算符,并且我们还重载了比较运算符 == 和 !=。我们还定义了一个友元函数,用于将Complex对象输出到标准输出流中。
您可以使用此类来执行各种操作。以下是一些示例:
```C++
Complex a(1, 2), b(3, 4);
Complex c = a + b; // c = (4, 6)
Complex d = a - b; // d = (-2, -2)
Complex e = a * b; // e = (-5, 10)
Complex f = a / b; // f = (0.44, 0.08)
a += b; // a = (4, 6)
b -= a; // b = (-1, -2)
c *= d; // c = (20, 0)
d /= e; // d = (0.08, -0.16)
bool equal = (a == b); // equal = false
bool not_equal = (a != b); // not_equal = true
cout << a << " " << b << " " << c << " " << d << endl; // 输出 (4,6) (-1,-2) (20,0) (0.08,-0.16)
```
希望这可以回答您的问题。
阅读全文