m0_68962183 2022-05-16 00:17 采纳率: 100%
浏览 129
已结题

定义复数类(Complex),包含必要的构造函数和析构函数,重载乘法赋值运算符“*=”实现复数与整数,复数与复数之间的乘法运算,自行举例并按格式输出

#要求达到的效果:
1.格式要求举例
c=2+3i
c*=5,c=10+15i
c*=4+5i,c=-7+22i
2.要求使用转换构造函数把整数转换为复数后进行运算
3.遇到的问题:数学逻辑不清晰
4.

using namespace std;

class Complex
{public:
Complex(){real=0;imag=0;}//定义构造函数
Complex(double r,double i){real=r;imag=i;}//构造函数重载
Complex operator*=(Complex &c2);
void display();
private:
    double real;
    double imag;
};
Complex Complex::operator*=(Complex &c1)
{Complex c;
    c.real=real*c1.real-imag*c1.imag;
    c.imag=real*c1.imag+imag*c1.real;
    
return c;}
void Complex::display()
{cout<<" "<<real<<"+"<<imag<<"i"<<endl;}
int main()
{Complex c1(2,3),c2=(4,5),c3;
c3=c1*=c2;
cout<<"c1*=";c1.display();
cout<<"c2*=";c2.display();
cout<<"c1*c2=";c3.display();
return 0;
}




  • 写回答

3条回答 默认 最新

  • 白驹_过隙 算法领域新星创作者 2022-05-16 09:54
    关注

    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
        cout<<"c=";
        print(c1);
     
        //与int类型相乘
        c1 *= 5;
        cout<<"c*=5,c=";
        print(c1);
     
        
        //与复数相乘
        cout<<"c*=4+5i,";
        Complex t(4, 5);
        c2 *= t;
        print(c2);
     
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 5月24日
  • 已采纳回答 5月16日
  • 创建了问题 5月16日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分