声明一个复数类 Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。例如,c1+c2,i+c1,c1+i均合法(设i为整数,c1,c2为复数)。
运行程序,分别求两个复数之和、整数和复数之和。
1.程序代码:
#include<iostream>
using namespace std;
class complex
{public:
complex() { real = 0; imag = 0; }
complex(double r, double i) { real = r; imag = i; }
complex(double r) { real = r; imag = 0; } //转换构造函数
friend complex operator+(complex c1, complex c2);
void display();
private:
double real;
double imag;
};
complex operator+(complex c1, complex c2)
{
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
void complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
complex c1(3, 5), c2(3, -10), c3, c4, c5;
c3 = c1 + c2;
c4 = 3 + c1;
c5 = c1 + 3;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << "c1+c2="; c3.display();
cout << "i+c1="; c4.display();
cout << "c1+i="; c5.display();
return 0;
}
2.运行结果: