#include <iostream>
using namespace std;
class complex
{
public:
complex(complex &c); //深度复制构造函数
complex(float r, float i); //普通构造函数
void set(float r, float i); //变量重新赋值
complex(); //无参构造函数
friend complex add(complex &b, complex &c); //相加
friend complex sub(complex &b, complex &c); //相减
friend complex mul(complex &b, complex &c); //相乘
void show();
private:
float real;
float imag;
};
complex::complex()
{
real = 0;
imag = 0;
}
complex::complex(float r , float i)
{
real = r;
imag = i;
}
complex::complex(complex &c)
{
real = c.real;
imag = c.imag;
}
void complex::set(float r, float i)
{
real = r;
imag = i;
}
void complex::show()
{
cout<<"result is:"<<real<<( imag>0 ? "+":"-")<<abs(imag)<<"i"<<endl; //abs()取绝对值函数
}
complex add(complex &b, complex &c)
{
float t1, t2;
t1 = b.real + c.real;
t2 = b.imag + c.imag;
return complex(t1, t2);
}
complex sub(complex &b, complex &c)
{
float t1, t2;
t1 = b.real - c.real;
t2 = b.imag - c.imag;
return complex(t1, t2);
}
complex mul(complex &b, complex &c)
{
float t1, t2 ;
t1 = b.real * c.real - b.imag * c.imag;
t2 = b.real * c.imag + c.real * b.imag;
return complex(t1, t2);
}
int main()
{
complex c1(3, 5);
complex c2(4, 8);
complex c3;
c3 = add(c1, c2); //调用赋值构造函数
c3.show();
c3 = sub(c1, c2);
c3.show();
c3 = mul(c1, c2);
c3.show();
return 0;
}
温馨提示:答案为网友推荐,仅供参考