「已注销」 2022-09-21 07:36 采纳率: 80%
浏览 44
已结题

C++重载的相关问题

一、完成复数类CComplex的定义,(包括real和image两个double型数据成员)
●包括构造函数,print()打印数据成员值的成员函数.
● 并用成员函数重载 ‘=’赋值运算符和前、后‘++’运算符,用友元函数重载双目‘+’和‘-’运算符.
二、在主函数中分别进行以下测试 :
●对象=对象+对象;
●对象=对象-对象;
●++对象;
并分别调用print函数打印对象数据成员值

  • 写回答

4条回答 默认 最新

  • 关注

    img

    代码如下:

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    class CComplex
    {
    private:
        double real, image;
    public:
        CComplex(double r = 0, double i = 0) { real = r; image = i; }
        ~CComplex() {}
        
    
        //友元函数+
        friend CComplex& operator +(CComplex& c1, CComplex& c2)
        {
            CComplex t;
            t.real = c1.real + c2.real;
            t.image= c1.image + c2.image;
            return t;
        }
        friend CComplex& operator -(CComplex& c1, CComplex& c2)
        {
            CComplex t;
            t.real = c1.real - c2.real;
            t.image = c1.image - c2.image;
            return t;
        }
    
        //成员函数=
        CComplex& operator =(CComplex& c)
        {
            CComplex t;
            t.real = c.image;
            t.image = c.image;
        }
    
        //前置++
        CComplex operator ++() {
            this->real += 1;
            this->image += 1;
            return *this;
        }
        //后置++
        CComplex operator ++(int) {
    
            CComplex c(this->real, this->image);
            this->real += 1;
            this->image += 1;
            return c;
        }
        //前置--
        CComplex operator --() {
            this->real -= 1;
            this->image -= 1;
            return *this;
        }
        //后置--
        CComplex operator --(int) {
    
            CComplex c(this->real, this->image);
            this->real -= 1;
            this->image -= 1;
            return c;
        }
    
        void print()
        {
            if (image > 0)
                cout << real << "+" << image << "i";
            else if (image == 0)
                cout << real;
            else
                cout << real << image << "i";
        }
    
    };
    
    
    
    
    int main()
    {
        CComplex a(3, 5), b(5, 3);
        cout << "a: ";
        a.print();
        cout << endl << "b: ";
        b.print();
        cout << endl << "a+b= ";
        CComplex c = a + b;
        c.print();
        cout << endl << "a-b= ";
        CComplex d = a - b;
        d.print();
    
        cout << endl << "++a : ";
        ++a;
        a.print();
    
    
        
        return 0;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 9月30日
  • 已采纳回答 9月22日
  • 创建了问题 9月21日

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?