题目:复数类四则运算及插入/提取操作
内容:为复数类Complex重载实现+,-,*,/,<<,>>等运算符,main(void)函数完成对其的测试。
Complex类结构说明:
Complex类的数据成员包括:
①私有数据成员:实部real(double型),虚部imag(double型)。
Complex类成员函数包括:
①有参构造函数Complex(double, double),其中参数默认值为0。
②重载运算符+以实现两个Complex的加法运算。
③重载运算符-以实现两个Complex的减法运算。
④重载运算符*以实现两个Complex的乘法运算。
⑤重载运算符/以实现两个Complex的除法运算。
⑥重载运算符<<以实现Complex对象的格式输出,输出格式要求:
<实部>+<虚部>i
例如:10.0,10.0+4.7i,10.0-4.7i,-4.7i,0等。
⑦重载运算符>>以实现Complex对象的格式输入,输入格式要求:
<实部>+<虚部>i
例如:10.0,10.0+4.7i,10.0-4.7i,-4.7i,0等。
测试样例:
```c++
#include <iostream>
using namespace std;
/*请在这里填写答案*/
int main() //主函数
{
Complex c1(1, 1), c2(-1, -1), c3; //定义复数类的对象
cin>>c1;
cout <<c1<<endl;
cout <<c2<<endl;
c3 = c1 - c2;
cout << c3<<endl;
c3 = c1 + c2;
cout << c3<<endl;
c3=c1 * c2;
cout << c3<<endl;
c3=c1 / c2;
cout << c3<<endl;
return 0;
}
输入样例:
10.0-4.7i
输出样例:
10-4.7i
-1-1i
11-3.7i
9-5.7i
-14.7-5.3i
-2.65+7.35i
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double _real = 0, double _imag = 0): real(_real), imag(_imag) {}
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 Complex& other) const {
return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
Complex operator/(const Complex& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
return Complex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator);
}
friend ostream& operator<<(ostream& os, const Complex& num) {
os << num.real;
if (num.imag > 0) {
os << "+" << num.imag << "i";
} else if (num.imag < 0) {
os << num.imag << "i";
}
return os;
}
friend istream& operator>>(istream& is, Complex& num) {
string input_str;
is >> input_str;
int plus_pos = input_str.find("+");
int minus_pos = input_str.find("-");
int i_pos = input_str.find("i");
if (plus_pos != string::npos) {
num.real = atof(input_str.substr(0, plus_pos).c_str());
num.imag = atof(input_str.substr(plus_pos + 1, i_pos - plus_pos - 1).c_str());
} else if (minus_pos != string::npos) {
num.real = atof(input_str.substr(0, minus_pos).c_str());
num.imag = atof(input_str.substr(minus_pos, i_pos - minus_pos + 1).c_str());
} else {
num.real = atof(input_str.c_str());
num.imag = 0;
}
return is;
}
};
int main() {
Complex a, b, c;
cout << "Please input a Complex number: ";
cin >> a;
cout << "Please input another Complex number: ";
cin >> b;
c = a + b;
cout << a << " + " << b << " = " << c << endl;
c = a - b;
cout << a << " - " << b << " = " << c << endl;
c = a * b;
cout << a << " * " << b << " = " << c << endl;
c = a / b;
cout << a << " / " << b << " = " << c << endl;
return 0;
}