描述 请重载复数类的流插入和流提取运算符,实现复数类的输出和输入。 #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; } 输入 实部和虚部以英文逗号分隔 输出 实部+虚部j 样例输入 样例一:5.4,-9.0 样例二:5.4,0 样例输出 样例一:5.4-9j 样例二:5.4
时间: 2024-01-07 20:05:17 浏览: 25
-9j
可以使用友元函数来重载流插入和流提取运算符,如下所示:
```cpp
#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 ostream & operator<<(ostream & os,const Complex & c) {
if(c.imag == 0) {
os << c.real;
} else if(c.real == 0) {
os << c.imag << "j";
} else {
os << c.real << (c.imag > 0 ? "+" : "") << c.imag << "j";
}
return os;
}
friend istream & operator>>(istream & is,Complex & c) {
string str;
is >> str;
int pos = str.find(",");
if(pos == string::npos) {
c.real = stod(str);
c.imag = 0;
} else {
c.real = stod(str.substr(0,pos));
c.imag = stod(str.substr(pos+1));
}
return is;
}
};
int main() {
Complex c;
cin >> c;
cout << c;
return 0;
}
```
在流插入运算符中,我们需要判断实部和虚部的值,如果其中一个为0,则只输出另一个;如果两者都不为0,则需要输出加号或减号以及j。
在流提取运算符中,我们可以先读入一个字符串,然后用find函数查找逗号的位置,如果没有逗号则说明只有实部,否则就有实部和虚部。最后使用substr函数提取出实部和虚部的值,并将其转换为double类型。