设计一复数类Complex,要求实现构造函数 释放函数和输出函数,并重载相加和相乘运算符;并编写主程序,调用

2025-04-16 22:06:17
推荐回答(1个)
回答(1):

#include
using std::cout;
using std::endl;

class CComplex
{
public:
CComplex(double real = 0.0, double m_image = 0.0);
void ShowComplex();
~CComplex(){}
friend CComplex operator +(const CComplex &c1, const CComplex &c2);
friend CComplex operator *(const CComplex &c1, const CComplex &c2);

private:
double m_real; //实部
double m_image; //虚部
};

CComplex::CComplex(double real, double image)
{
m_real = real;
m_image = image;
}

void CComplex::ShowComplex()
{
cout << m_real << "+" << m_image << "i" <}

CComplex operator +(const CComplex &c1, const CComplex &c2)
{
return CComplex(c1.m_real+c2.m_real, c1.m_image+c2.m_image);
}

CComplex operator *(const CComplex &c1, const CComplex &c2)
{
return CComplex(c1.m_real*c2.m_real-c1.m_image*c2.m_image,
c1.m_real*c2.m_image+c1.m_real*c2.m_image);
}

int main()
{
CComplex c1(2, 3), c2(4, 6), c3;

c1.ShowComplex();
c2.ShowComplex();

c3 = c1 + c2;
c3.ShowComplex();

c3 = c1 * c2;
c3.ShowComplex();

return 0;
}