/**
* 04737 c++ 自学考试2019版
* 第四章程序设计题1
* 为程序4-2中的类myComplex重载乘法运算符
*/
#include <iostream>//标准流
using namespace std;//标准命名空间
class myComplex
{
private:
double real,image;
public:
myComplex():real(0),image(0){};//无参构造
myComplex(double r,double i):real(r),image(i){};//有参构造
~myComplex(){}//空析构
//声明友元重载+
friend myComplex operator+(const myComplex &c1,const myComplex &c2);
//声明友元重载*
friend myComplex operator*(const myComplex &c1,const myComplex &c2);
//声明友元重载-
friend myComplex operator-(const myComplex &c1,const myComplex &c2);
//打印
void print();
};
//定义友元重载+
myComplex operator+(const myComplex &c1,const myComplex &c2)
{
return myComplex(c1.real+c2.real,c1.image+c2.image);
}
//定义友元重载-
myComplex operator-(const myComplex &c1,const myComplex &c2)
{
return myComplex(c1.real-c2.real,c1.image-c2.image);
}
//定义友元重载*
myComplex operator*(const myComplex &c1,const myComplex &c2)
{
return myComplex(c1.real*c2.real-c1.image*c2.image,c1.image*c2.real+c2.image*c1.real);
}
//打印
void myComplex::print()
{
cout<<"real:"<<this->real<<endl;
cout<<"image:"<<this->image<<endl;
}
int main()
{
myComplex c1(1,2),c2(3,4);
(c1*c2).print();
}

相关推荐