请完成Complex类的定义,使得下面的主函数能正常运行。 int main( ) { Complex c1(1,2); cout<<"c1="<<c1; Complex c2(2); cout<<"c2="<<c2<<endl; Complex c3(c1); cout<<"c3="<<c3; c1=c1+c2+c3; // c1=(c1.operator+(c2)).operator+(c3); cout<<"c1=c1+c2+c3="<<c1; c2=-c3; cout<<"c2=-c3="<<c2; c3=c2-c1; cout<<"c3=c2-c1="<< c3; Complex r2=2+c2; cout<<"r2=2+c2="<<r2; Complex c4; cin>>c4; cout<<"c4="<<c4; cout<<"the module of c4 is: "<<c4.GetMagnitude()<<endl; return 0; }
时间: 2023-10-30 16:10:31 浏览: 108
```
#include <iostream>
#include <cmath>
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& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator-() const {
return Complex(-real, -imag);
}
Complex operator+(double num) const {
return Complex(real + num, imag);
}
Complex operator-(double num) const {
return Complex(real - num, imag);
}
friend Complex operator+(double num, const Complex& c) {
return c + num;
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
friend istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
double GetMagnitude() const {
return sqrt(real * real + imag * imag);
}
};
int main() {
Complex c1(1, 2);
cout << "c1=" << c1;
Complex c2(2);
cout << "c2=" << c2 << endl;
Complex c3(c1);
cout << "c3=" << c3;
c1 = c1 + c2 + c3;
cout << "c1=c1+c2+c3=" << c1;
c2 = -c3;
cout << "c2=-c3=" << c2;
Complex c4;
cin >> c4;
cout << "c4=" << c4;
cout << "the module of c4 is: " << c4.GetMagnitude() << endl;
return 0;
}
```
阅读全文