源程序:
#include <iostream>
#include <iomanip>
using namespace std;
class myComplex
{
private:
double real, imag;
public:
myComplex();
myComplex(double r,double i);
~myComplex() {};
friend myComplex operator+(const myComplex &c1, const myComplex &c2);
friend myComplex operator*(const myComplex &c1, const myComplex &c2);
void output();
};
myComplex::myComplex()
{
real = 0;
imag = 0;
}
myComplex::myComplex(double r, double i)
{
real = r;
imag = i;
}
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, c1.imag*c2.real + c1.real*c2.imag);
}
void myComplex::output()
{
cout << real << setiosflags(ios::showpos)<<imag << "i" << endl;
}
int main()
{
myComplex c1(1, 2), c2(3, 4), res,res1;
res = c1 + c2;
res1 = c1 * c2;
cout << "两个复数相加,结果为:";
res.output();
cout << endl;
cout << "两个复数相乘,结果为:";
res1.output();
cout << endl;
system("pause");
return 1;
}
运行结果: