#include<iostream> #include<cmath> using namespace std; class Complex{ private: int real; int imag; public: Complex(int r=0,int i=0):real(r),imag(i){} Complex operator+(Complex &b); void display(){ cout<<real<<"+"<<imag<<"i";} }; Complex::Complex operator+(Complex &b){ Complex c; c.real=real+b.real; c.imag=imag+b.imag; return c; } int main(){ Complex c1(1,1),c2(2,2),c3; c3=c2+c1; c3.display(); return 0; }
时间: 2024-04-13 13:29:06 浏览: 104
#include <iostream>
你提供的代码存在一些语法错误。在Complex类中,你定义了一个重载的加法运算符,但是函数定义的位置有误。以下是修改后的代码:
```cpp
#include<iostream>
#include<cmath>
using namespace std;
class Complex{
private:
int real;
int imag;
public:
Complex(int r=0, int i=0) : real(r), imag(i) {}
Complex operator+(Complex &b);
void display(){
cout << real << "+" << imag << "i";
}
};
Complex Complex::operator+(Complex &b){
Complex c;
c.real = real + b.real;
c.imag = imag + b.imag;
return c;
}
int main(){
Complex c1(1, 1), c2(2, 2), c3;
c3 = c2 + c1;
c3.display();
return 0;
}
```
在这个代码中,我们定义了一个Complex类,表示复数。在类中,我们重载了加法运算符,使得两个Complex对象可以相加。在main函数中,创建了两个Complex对象c1和c2,并将它们相加得到c3。最后输出c3的值。
阅读全文