定义一个复数类 Complex,重载运算符“+” ,使之能用于复数的加法运算。 参加运 算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。例如,c1+c2,i+c1,c1+i均合法(设i为整数,c1,c2为复数)。用 c++编写程序,分别求两个复数之和、整数和复数之和。
时间: 2023-05-31 10:07:31 浏览: 129
没问题,以下是代码实现:
```c++
#include<iostream>
using namespace std;
class Complex{
private:
double _real,_image;
public:
Complex(double real=0,double image=0):_real(real),_image(image){};
Complex operator+(const Complex &c);
friend Complex operator+(const int num,const Complex &c);
friend ostream& operator<<(ostream& out,const Complex &c);
};
Complex Complex::operator+(const Complex &c){
return Complex(_real+c._real,_image+c._image);
}
Complex operator+(const int num,const Complex &c){
return Complex(num+c._real,c._image);
}
ostream& operator<<(ostream& out,const Complex &c){
out<<"("<<c._real<<","<<c._image<<"i)";
return out;
}
int main(){
Complex c1(1,2);
Complex c2(2,3);
int i=3;
Complex c3=c1+c2;
Complex c4=i+c1;
cout<<"c1+c2="<<c3<<endl;
cout<<"i+c1="<<c4<<endl;
return 0;
}
```
输出结果为:
```
c1+c2=(3,5i)
i+c1=(4,2i)
```
阅读全文