定义复数类complex,并使用友元函数实现复数的加法,减法,乘法,所有函数都返回c

都返回complex对象。

#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;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-11-14
#include<iostream.h>
class Complex
{
double real;
double image;
public:
Complex(double r = o,double i = 0)
{
real=r;
image = i;
}
friend void inputcomplex(Complex &comp);
friend Complex addcomplex(Complex &c1,Complex &c2);
friend Complex subcomplex(Complex &c1,Complex &c2);
friend Complex mulcomplex(Complex &c1,Complex &c2);
friend void outputcomplex(Complex &comp);
};
void inputcomplex(Complex &comp)
{
cin>>comp.real>>comp.image;
}
Complex addcomplex(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real + c2.real;
c.image=c1.image+c2.image;
return c;
}
Complex subcomplex(Complex &c1,Complex &c2)
{
Complex c;
c.real = c1.real - c2.real;
c.image= c1.image - c2.image;
return c;
}
Complex mulcomplex(Complex &c1,Complex &c2)
{
Complex c;
c.real = c1.real*c2.real-c1.image*c2.image;
c.image = c1.real * c2.image + c1.image * c2.real;
return c;
}
void putcomplex(Complex &comp)
{
cout<<"("<<comp.real<<","<<comp.image <<")";
}
void main()
{
Complex c1,c2,result;
cout<<"请输入第一个复数的实部和虚部:"<<endl;
inputcomplex(c1);
cout<<"请输入第二个复数的实部和虚部:"<<endl;
inputcomplex(c2);
result=addcomplex(c1,c2);
outputcomplex(c1);
cout<<"+";
outputcomplex(c2);
cout<<"=";
outputcomplex(result);
cout<<"\n.................."<<endl;
result = subcomplex(c1,c2);
outputcomplex(c1);
cout<<"-";
outputcomplex(c2);
cout<<"=";
outputcomplex(result);
cout<<"\n.................."<<endl;
result = mulcomplex(c1,c2);
outputcomplex(c1);
cout<<"*";
outputcomplex(c2);
cout<<"=";
outputcomplex(result);
cout<<endl;
}