用C++定义一个复数类,在类中分别重载流插入运算符“<<”和流 提取运算符“>>”,使之实现复数的输入和输出功能。在主函数中, 分别使用运算符“<<”和“>>”,实现对复数类对象的输入和输出。
时间: 2023-12-03 20:43:45 浏览: 86
C++实现复数的运算
以下是一个简单的复数类的定义,其中重载了流插入运算符“<<”和流提取运算符“>>”,实现了复数的输入和输出功能。
```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) {}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
friend istream& operator>>(istream& is, Complex& c) {
cout << "Enter real part: ";
is >> c.real;
cout << "Enter imaginary part: ";
is >> c.imag;
return is;
}
};
int main() {
Complex c1, c2;
cout << "Enter a complex number: ";
cin >> c1;
cout << "You entered: " << c1 << endl;
cout << "Enter another complex number: ";
cin >> c2;
cout << "You entered: " << c2 << endl;
return 0;
}
```
在主函数中,我们通过使用运算符“<<”和“>>”,实现对复数类对象的输入和输出。用户可以输入实部和虚部,程序会自动输出对应的复数。
阅读全文