7-5 复数的输入输出运算符重载
时间: 2024-05-05 18:19:32 浏览: 381
对于复数的输入输出运算符重载,可以定义如下:
```c++
#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0):real(r), imag(i) {}
friend std::ostream& operator<<(std::ostream& os, const Complex& c);
friend std::istream& operator>>(std::istream& is, Complex& c);
};
std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << "(" << c.real << "," << c.imag << ")";
return os;
}
std::istream& operator>>(std::istream& is, Complex& c) {
std::cout << "Enter Real Part: ";
is >> c.real;
std::cout << "Enter Imaginary Part: ";
is >> c.imag;
return is;
}
int main() {
Complex c;
std::cin >> c;
std::cout << "The Complex Number is: " << c << std::endl;
return 0;
}
```
运行结果如下:
```
Enter Real Part: 7
Enter Imaginary Part: -5
The Complex Number is: (7,-5)
```
阅读全文