习题 10.3 定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。例如:c1+c2,i+c1,c1+i均合法(设i为整数,c1,c2位复数)。编程序,分别求两个复数之和、整数和复数之和。
代码:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0.0,double i = 0.0):real(r),imag(i) {}
friend Complex operator + (Complex& , Complex& );
friend Complex operator + (Complex& , double& );
friend Complex operator + (double& , Complex& );
void display();
private:
double real;
double imag;
};
void Complex::display()
{
cout << "(" << real << "," << imag << ")" << endl;
}
int main()
{
Complex c1(10, 5), c2(2, -2), c3, c4, c5;