#include<iostream> using namespace std; class Complex { private: double real, image; public: Complex(double rel = 0, double img = 0) { real = rel; image = img; } void display() { cout << "(" << real; if (image > 0) cout << "+" << image << "*i)"; else if (image < 0) cout << image << "*i)"; else cout << ")"; } friend Complex operator -( Complex& c1, const Complex& c2); friend Complex operator /( Complex& c1, const Complex& c2); friend Complex operator ==(Complex& c1, Complex& c2); friend Complex operator !=(Complex& c1, Complex& c2); friend ostream operator <<(Complex& c1, Complex& c2); }; Complex operator -( Complex& c1, const Complex& c2) { Complex temp; temp.real = c1.real - c2.real; temp.image = c1.image - c2.image; return temp; } Complex operator /( Complex& c1, const Complex& c2) { Complex FFF; FFF.real = c1.real / c2.real; FFF.image = c1.image / c2.image; return FFF; } int main() { Complex c1(10, 9), c2(3, -4), c3; c3 = c1 / 5; c1.display(); cout << "/"; cout << 5; cout << "="; c3.display(); cout << endl; return 0; //输出比较的结果 cout<<"c1==c2 ? 结果:"; cout<<(c1==c2)<<endl; cout<<"c1!=c2 ? 结果:"; cout<<(c1!=c2)<<endl; }严重性 代码 说明 项目 文件 行 禁止显示状态 错误 C2678 二进制“<<”: 没有找到接受“std::ostream”类型的左操作数的运算符(或没有可接受的转换)帮我修改并给出正确代码
时间: 2024-03-20 08:45:05 浏览: 106
需要将友元函数的返回类型改为 ostream&,并在函数内部将输出语句改为 return os,同时在 main 函数内输出对象的语句需要改为 cout << c1 << endl; 和 cout << c2 << endl;。代码如下:
```
#include<iostream>
using namespace std;
class Complex {
private:
double real, image;
public:
Complex(double rel = 0, double img = 0) {
real = rel;
image = img;
}
void display() {
cout << "(" << real;
if (image > 0)
cout << "+" << image << "*i)";
else if (image < 0)
cout << image << "*i)";
else
cout << ")";
}
friend Complex operator -(Complex& c1, const Complex& c2);
friend Complex operator /(Complex& c1, const Complex& c2);
friend bool operator ==(Complex& c1, Complex& c2);
friend bool operator !=(Complex& c1, Complex& c2);
friend ostream& operator <<(ostream& os, Complex& c);
};
Complex operator -(Complex& c1, const Complex& c2) {
Complex temp;
temp.real = c1.real - c2.real;
temp.image = c1.image - c2.image;
return temp;
}
Complex operator /(Complex& c1, const Complex& c2) {
Complex FFF;
FFF.real = c1.real / c2.real;
FFF.image = c1.image / c2.image;
return FFF;
}
bool operator ==(Complex& c1, Complex& c2) {
return (c1.real == c2.real) && (c1.image == c2.image);
}
bool operator !=(Complex& c1, Complex& c2) {
return !(c1 == c2);
}
ostream& operator <<(ostream& os, Complex& c) {
os << "(" << c.real;
if (c.image > 0)
os << "+" << c.image << "*i)";
else if (c.image < 0)
os << c.image << "*i)";
else
os << ")";
return os;
}
int main() {
Complex c1(10, 9), c2(3, -4), c3;
c3 = c1 / 5;
c1.display();
cout << "/";
cout << 5;
cout << "=";
c3.display();
cout << endl;
cout << "c1 == c2 ? 结果:";
cout << (c1 == c2) << endl;
cout << "c1 != c2 ? 结果:";
cout << (c1 != c2) << endl;
cout << c1 << endl;
cout << c2 << endl;
return 0;
}
```
阅读全文