栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ ——重载乘法赋值运算符“*=”实现复数与整数、复数与复数之间的乘法运算

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ ——重载乘法赋值运算符“*=”实现复数与整数、复数与复数之间的乘法运算

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

 

#include 
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号