定义并实现Complex类

定义并实现Complex类

设计、定义并实现Complex类

 #include <iostream>
#include <cmath>
using namespace std;
class MyComplex
{
public:
MyComplex(double aa=,double bb=);
MyComplex(MyComplex &pp);
void add(MyComplex tt);
void show();
double qumo();
private:
double reality;
double imaginary;
};
MyComplex::MyComplex(double aa,double bb)
{
reality=aa;
imaginary=bb;
}
MyComplex::MyComplex(MyComplex &pp)
{
reality=pp.reality;
imaginary=pp.imaginary;
}
void MyComplex::add(MyComplex tt)
{
reality+=tt.reality;
imaginary+=tt.imaginary;
}
void MyComplex::show()
{
cout<<reality<<"+"<<imaginary<<"i"<<endl;
}
double MyComplex::qumo()
{
double mo;
mo=sqrt(reality*reality+imaginary*imaginary);
return mo;
}
int main ()
{
double result;
MyComplex c1(,);
MyComplex c2(4.5);
MyComplex c3(c1);
c1.add(c2);
c1.show();
result=c3.qumo();
cout<<result<<endl;
return ;
}

设计、定义并实现Complex类-LMLPHP

输出结果为复数c1和c2的和,以及c3的模数。

由于这个类里的加法函数和常规习惯有出入,所以修改为下面的重载函数形式:

 #include <iostream>
#include <cmath>
using namespace std;
class MyComplex
{
public:
MyComplex(double aa=,double bb=);
MyComplex(MyComplex &pp);
void add(MyComplex tt,MyComplex rr);
void add(MyComplex tt);
void show();
double qumo();
private:
double reality;
double imaginary;
};
MyComplex::MyComplex(double aa,double bb)
{
reality=aa;
imaginary=bb;
}
MyComplex::MyComplex(MyComplex &pp)
{
reality=pp.reality;
imaginary=pp.imaginary;
}
void MyComplex::add(MyComplex tt,MyComplex rr)
{
reality=tt.reality+rr.reality;
imaginary=tt.imaginary+rr.imaginary;
}
void MyComplex::add(MyComplex tt)
{
reality+=tt.reality;
imaginary+=tt.imaginary;
}
void MyComplex::show()
{
cout<<reality<<"+"<<imaginary<<"i"<<endl;
}
double MyComplex::qumo()
{
double mo;
mo=sqrt(reality*reality+imaginary*imaginary);
return mo;
}
int main ()
{
double result;
MyComplex c1(,);
MyComplex c2(4.5);
MyComplex c3(c1);
MyComplex c4;
c4.add(c1,c2);
c1.add(c2);
c4.show();
c1.show();
result=c3.qumo();
cout<<result<<endl;
return ;
}

设计、定义并实现Complex类-LMLPHP

一种是把结果保存在加数c1中,另一种是保存在另一个复数对象c4中。

实验总结:

(1)当要求的操作方式可以改进时可以尝试进行改进。

(2)成员函数的形参个数 是否需要默认形参值 是否需要返回值 返回值类型 都需要结合函数的作用适当选择。

05-11 11:06