题目2:实现复数类,具体要求如下:
(1)数据成员包含实部real与虚部image;
(2)构造函数:给复数的数据成员赋初值。如果不给任何初始值,则默认实部real=虚部image=0;
(3)设计成员函数和友元函数实现复数的加减运算。
主函数
int main()
{
Complex c1(2, 1), c2(6, -2), c3(-2, -1);
cout<<"c1= ";
c1.show();
cout<<"c2= ";
c2.show();
cout<<"c3= ";
c3.show();
Complex c4 = c1.Add(c2);
cout<<"c4 = c1+c2 = ";
c4.show();
Complex c5 = c1.Sub(c2);
cout<<"c5 = c1-c2 = ";
c5.show();
cout<<"c6 = c1+c3 = ";
Complex c6 = Add_two_c(c1, c3);
c6.show();
cout<<"c7 = c6-c3 = ";
Complex c7 = Sub_two_c(c6, c3);
c7.show();
return 0;
}
解题思路:
首先定义一个Complex的类,该类有两个私有成员变量real和image,分别表示复数的实部和虚部,接着定义了一个构造函数,它接受两个参数,如果没有提供参数,则默认值为0。接着写出用show函数打印复数的值,分实部和虚部多种情况考虑,接着用成员函数Add和Sub函数分别计算两个复数的和与差,接着声明友元函数Add_two_c和Sub_two_c实现加法和减法。
代码:
#include <iostream>
using namespace std;
class Complex
{
private:
double real;
double image;
public:
Complex(double r = 0,double i = 0)
:real(r),image(i){}
void show()const
{
if(real == 0 && image == 0)
{
cout<<0<<endl;
}
else if(real != 0 && image == 0)
{
cout<<real<<endl;
}
else if(real == 0 && image != 0)
{
if(image == 1)
{
cout<<"i"<<endl;
}
else if(image == -1)
{
cout<<"-"<<"i"<<endl;
}
else
{
cout<<image<<"i"<<endl;
}
}
else if(real != 0 && image != 0)
{
if(image < 0)
{
if(image == -1)
{
cout<<real<<"-"<<"i"<<endl;
}
else
{
cout<<real<<image<<"i"<<endl;
}
}
else if(image > 0)
{
if(image == 1)
{
cout<<real<<"+"<<"i"<<endl;
}
else
{
cout<<real<<"+"<<image<<"i"<<endl;
}
}
}
}
Complex Add(const Complex& other)const
{
return Complex(real + other.real,image + other.image);
}
Complex Sub(const Complex& other)const
{
return Complex(real - other.real,image - other.image);
}
friend Complex Add_two_c(const Complex& a, const Complex& b);
friend Complex Sub_two_c(const Complex& a, const Complex& b);
};
Complex Add_two_c(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.image + b.image);
}
Complex Sub_two_c(const Complex& a, const Complex& b) {
return Complex(a.real - b.real, a.image - b.image);
}
int main()
{
Complex c1(2, 1), c2(6, -2), c3(-2, -1);
cout<<"c1= ";
c1.show();
cout<<"c2= ";
c2.show();
cout<<"c3= ";
c3.show();
Complex c4 = c1.Add(c2);
cout<<"c4 = c1+c2 = ";
c4.show();
Complex c5 = c1.Sub(c2);
cout<<"c5 = c1-c2 = ";
c5.show();
cout<<"c6 = c1+c3 = ";
Complex c6 = Add_two_c(c1, c3);
c6.show();
cout<<"c7 = c6-c3 = ";
Complex c7 = Sub_two_c(c6, c3);
c7.show();
return 0;
}
运行结果截图: