定义复数类(Complex)

C++ 编写程序 :包含必要的构造函数和析构函数,重载乘法赋值运算符“*=”实现复数与整数、复数与复数之间的乘法运算,自行举例并按照如下格式输出计算结果。(要求使用转换构造函数把整数转换为复数后进行计算)。
输出格式示例:

img

##怎么把输入的整数转为复数?
##这里的构造函数和析构函数有什么作用(真的不太理解)🙏

代码及运行结果如下:

img

#include <iostream>
using namespace std;
class Complex
{
public:
    int real;
    int image;
public:
    Complex(int r, int i)
    {
        real = r; image = i;
    }
    Complex(int r)
    {
        real = r; image = 0;
    }
    Complex()
    {
        real = 0; image = 0;
    }

    ~Complex()
    {
        //do nothing
    }
    Complex operator *= (const Complex Right) 
    {
        int a = real, b = image;
        real = a * Right.real - b * Right.image;
        image = b * Right.real + a * Right.image;
        return *this;
    }

    Complex operator *= (const int n) 
    {
        Complex t(n, 0);
        *this *= t;
        return *this;
    }
    friend void print(Complex comp);

};


void print(Complex comp)
{
    cout << comp.real;
    if (comp.image < 0)
        cout << comp.image << "i" << endl;
    else if (comp.image > 0)
        cout <<"+" << comp.image << "i" << endl;
}

int main()
{
    Complex c1(2, 3);
    Complex c2(2, 3);
    
    
    //显示C1
    print(c1);

    //与int类型相乘
    c1 *= 5;
    print(c1);

    
    //与复数相乘
    Complex t(4, 5);
    c2 *= t;
    print(c2);

    return 0;
}

构造就是制作,析构就是摧毁

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632