请重载复数类的流插入和流提取运算符,实现复数类的输出和输入。 #include<iostream> #include <string> using namespace std; //--------------------- class Complex { private: double real,imag; public: Complex(){ real=imag=0; } Complex(double r){ real=r;imag=0; } Complex(double r,double i){ real=r;imag=i; } // 在此处补充你的代码 int main() { Complex c; cin>>c; cout<<c; }
时间: 2024-01-07 10:04:19 浏览: 79
C++ 流插入和流提取运算符的重载的实现
在此处给出复数类的流插入和流提取运算符的实现:
```c++
#include<iostream>
#include <string>
using namespace std;
class Complex {
private:
double real,imag;
public:
Complex() {
real = imag = 0;
}
Complex(double r) {
real = r;
imag = 0;
}
Complex(double r, double i) {
real = r;
imag = i;
}
friend istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << "i)";
return os;
}
};
int main() {
Complex c;
cin >> c;
cout << c;
return 0;
}
```
在以上代码中,我们使用了 `friend` 关键字来声明流插入和流提取运算符的友元关系,这样就可以直接访问 `Complex` 类的私有成员变量。在流插入运算符中,我们输出复数的实部和虚部;在流提取运算符中,我们从输入流中读取两个浮点数,分别为复数的实部和虚部。
阅读全文