#include<iostream> using namespace std; class Complex { private: double real; double imag; public: Complex(double r=0.0,double i=0.0) { real = r; imag = i; } friend Complex operator + (Complex c1, Complex c2); friend Complex operator - (Complex c1, Complex c2); void display(); }; Complex Complex:: operator +(Complex c1, Complex c2) { Complex c; c.real = c1.real + c2.real; c.imag = c1.imag + c2.imag; return c; } Complex Complex:: operator -(Complex c1, Complex c2) { Complex c; c.real = c1.real - c2.real; c.imag = c1.imag - c2.imag; return c; } void Complex::display() { cout << "(" << real << "," << imag << ")" << endl; } int main() { Complex c1(4, 3), c2(2, 1), c3; cout << "c1="; c1.display(); cout << "c2="; c2.display(); c3 = c1 - c2; cout << "c3="; c3.display(); c3 = c1 + c2; cout << "c3="; c3.display(); return 0; } 存在的问题
时间: 2023-06-26 13:06:34 浏览: 138
代码中存在以下问题:
1. 缺少头文件:需要添加头文件 `#include<iostream>`。
2. 命名空间使用不规范:应该避免在头文件中使用 `using namespace std;`,而是应该在使用标准库的时候显式地使用 `std::`。
3. 运算符重载函数的定义方式不正确:应该将运算符重载函数定义为类的成员函数,或者定义为友元函数。在代码中,运算符重载函数应该写成 `Complex Complex::operator+(Complex c2)` 和 `Complex Complex::operator-(Complex c2)`。
4. 运算符重载函数的参数传递方式不正确:在运算符重载函数中,需要将当前对象作为一个参数传入。在代码中,应该将运算符重载函数定义为友元函数,并且将两个对象作为参数传入,在函数中分别访问它们的私有成员变量。
5. 类方法的定义方式不规范:在定义类方法时,应该将方法的实现写在类定义的外面,而不是写在类定义内部。
6. 对象的初始化方式不规范:在定义对象时,应该避免使用默认构造函数的方式进行初始化,而是应该使用带参数的构造函数进行初始化。在代码中,应该将 `Complex c1(4, 3), c2(2, 1), c3;` 改为 `Complex c1(4, 3), c2(2, 1), c3(0, 0);`。
下面是修改后的代码:
```c++
#include<iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r=0.0, double i=0.0) {
real = r;
imag = i;
}
Complex operator+(Complex c2);
Complex operator-(Complex c2);
void display();
};
Complex Complex::operator+(Complex c2) {
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
Complex Complex::operator-(Complex c2) {
Complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
void Complex::display() {
std::cout << "(" << real << "," << imag << ")" << std::endl;
}
int main() {
Complex c1(4, 3), c2(2, 1), c3(0, 0);
std::cout << "c1=";
c1.display();
std::cout << "c2=";
c2.display();
c3 = c1 - c2;
std::cout << "c3=";
c3.display();
c3 = c1 + c2;
std::cout << "c3=";
c3.display();
return 0;
}
```
阅读全文