在C++中,定义一个复数类,定义复数的常规运算,包括+,-,*,/, 重载运算符<<,>>, 使之可以输入和输出复数。输入输出的格式为 a+bi。
时间: 2024-06-13 21:08:33 浏览: 14
以下是一个C++中复数类的定义,包括常规运算符的重载和输入输出格式的定义:
```cpp
#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 denominator = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
friend istream& operator>>(istream& is, Complex& c) {
char plus_sign, i;
is >> c.real >> plus_sign >> c.imag >> i;
return is;
}
};
int main() {
Complex c1(1, 2), c2(3, 4);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
cout << "c1 + c2 = " << c1 + c2 << endl;
cout << "c1 - c2 = " << c1 - c2 << endl;
cout << "c1 * c2 = " << c1 * c2 << endl;
cout << "c1 / c2 = " << c1 / c2 << endl;
Complex c3;
cout << "请输入一个复数(格式为a+bi):";
cin >> c3;
cout << "您输入的复数为:" << c3 << endl;
return 0;
}
```