源程序:
//
// main.cpp
// p154
//
// Created by duanqibo on 2019/12/18.
// Copyright © 2019年 duanqibo. All rights reserved.
//
#include <iostream>
using namespace std;
class myComplex
{
private:
double real,imag;
public:
myComplex()
{
real=0;
imag=0;
}
myComplex(double r,double i)
{
real=r;
imag=i;
}
void outCom();
myComplex operator-(const myComplex &c);
friend myComplex operator+(const myComplex &c1,const myComplex &c2);
friend myComplex operator-(const myComplex &c1,const myComplex &c2);
friend myComplex operator-(const myComplex &c1,double r);
friend myComplex operator-(double r,const myComplex &c1);
};
myComplex operator+(const myComplex &c1,const myComplex &c2)
{
return myComplex(c1.real+c2.real,c1.imag+c2.imag);
}
myComplex operator-(const myComplex &c1,const myComplex &c2)
{
return myComplex(c1.real-c2.real,c1.imag-c2.imag);
}
myComplex operator-(const myComplex &c1,double r)
{
return myComplex(c1.real-r,c1.imag);
}
myComplex operator-(double r,const myComplex &c1)
{
return myComplex(r-c1.real-r,-c1.imag);
}
void myComplex::outCom()
{
cout<<"("<<real<<","<<imag<<")";
}
int main(int argc, const char * argv[])
{
// insert code here...
myComplex c1(1,2),c2(3,4),res;
c1.outCom();
cout<<"operator+";
c2.outCom();
cout<<"=";
res=c1+c2;
res.outCom();
cout<<endl;
res=c1-5;
res.outCom();
cout<<endl;
res=5-c1;
res.outCom();
cout<<endl;
return 0;
}
运行结果: