#include<iostream> using namespace std; class Complex{ public: Complex(double r=0,double i=0):real(r),imga(i){ } friend Complex operator + (const Complex &c1,const Complex &c2); friend Complex operator - (Complex c1,Complex c2); friend ostream & operator <<(ostream &out,const Complex &c) private: double real,imga; }; Complex operator + (const Complex &c1,const Complex &c2) const{ return (c1.real + c2.real,c1.imga + c2.imga); } Complex operator - (const Complex &c2) const{ return (c1.real - c2.real,c1.imga - c2.imga); } ostream operator << (ostream &out ,const Complex &c) { out<<"("<<c.real<<","<<c.imga<<")"<<endl; return out; }这段代码有什么问题
时间: 2024-03-02 13:53:24 浏览: 86
#include_iostream.h_
4星 · 用户满意度95%
这段代码有一些问题:
1. 在 Complex 类中,`operator +` 和 `operator -` 的定义中都使用了 `const` 修饰参数,但是在函数体内却使用了非 const 成员函数 `real` 和 `imga`,这是不合法的。
2. 在 `operator +` 和 `operator -` 的定义中,返回值应该是 `Complex` 类型,而不是使用逗号运算符后返回的结果。
3. 在 `operator -` 的定义中,函数名后的参数应该是 `Complex c1` 而不是 `Complex c2`。
4. 在 `operator <<` 的定义中,函数名后的返回值应该是 `ostream&` 而不是 `ostream`。
下面是修改后的代码:
```
#include<iostream>
using namespace std;
class Complex{
public:
Complex(double r = 0, double i = 0) : real(r), imga(i) {
}
friend Complex operator +(const Complex &c1, const Complex &c2);
friend Complex operator -(const Complex &c1, const Complex &c2);
friend ostream & operator <<(ostream &out, const Complex &c);
private:
double real, imga;
};
Complex operator +(const Complex &c1, const Complex &c2) {
return Complex(c1.real + c2.real, c1.imga + c2.imga);
}
Complex operator -(const Complex &c1, const Complex &c2) {
return Complex(c1.real - c2.real, c1.imga - c2.imga);
}
ostream& operator << (ostream &out, const Complex &c) {
out << "(" << c.real << "," << c.imga << ")" << endl;
return out;
}
int main() {
Complex a(1, 2), b(3, 4);
cout << a + b << endl;
cout << a - b << endl;
return 0;
}
```
阅读全文