运算符重载

复制代码
#include <iostream>
using namespace std;
class Num
{
private:
    int num1; //实部
    int num2; //虚部
public:
    Num(){}; //无参构造
    Num(int n1,int n2):num1(n1),num2(n2){}; //有参构造
    ~Num(){}; //析构函数
    const Num operator+(const Num &other)const  //加号重载
    {
        Num a; //定义临时类对象
        a.num1 = num1 + other.num1; //实部相加
        a.num2 = num2 + other.num2; //虚部相加
        return  a;
    }
    bool operator==(const Num &other)const //相等重载
    {
        //判断实部虚部是否分别相等
        if(num1 == other.num1 && num2 == other.num2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    Num &operator+=(const Num &other)  //加等重载
    {
        //实部虚部分别加等于
        num1 += other.num1;
        num2 += other.num2;
        return *this;
    }
    Num &operator++()  //重载前置++
    {
        ++num1;
        ++num2;
        return *this;
    }
    Num &operator++(int) //重载后置++
    {
        num1++;
        num2++;
        return *this;
    }
    Num operator-()const  //重载-
    {
        Num temp;
        temp.num1 = -num1;
        temp.num2 = -num2;
        return temp;
    }
    void init(int n1,int n2)  //修改类中的值
    {
        num1 = n1;
        num2 = n2;
    }
    void show() //展示
    {
        if(num2 < 0)
        {
            cout << num1 << num2 << "j" << endl;
        }
        else
        {
            cout << num1 << "+" << num2 << "j" << endl;

        }
    }
};


int main()
{
    Num n1;      //调用无参构造
    Num n2(4,3); //调用有参构造
    n1.show();   //调用展示函数
    cout << "*********************" << endl;
    n1.init(4,2);    //调用修改函数
    n1.show();
    cout << "*********************" << endl;
    n1++;
    n1.show();
    cout << "*********************" << endl;
    ++n1;
    n1.show();
    cout << "*********************" << endl;
    if(n1 == n2)  // 调用重载的相等函数
    {
        cout << "true" << endl;
    }
    else
    {
        cout << "false" << endl;
    }
    cout << "*********************" << endl;
    n1 += n2; //调用加等于重载函数
    n1.show();
    cout << "*********************" << endl;
    n1 = -n2; //调用重载-
    n2.show();
    return 0;
}
相关推荐
JCBP_44 分钟前
QT(4)
开发语言·汇编·c++·qt·算法
会开花的二叉树1 小时前
继承与组合:C++面向对象的核心
java·开发语言·c++
潮汐退涨月冷风霜2 小时前
数字图像处理(1)OpenCV C++ & Opencv Python显示图像和视频
c++·python·opencv
第七序章3 小时前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
逆小舟5 小时前
【Linux】人事档案——用户及组管理
linux·c++
风中的微尘10 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某10 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
小冯记录编程11 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
C_Liu_11 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan11 小时前
【C++】类和对象1
java·开发语言·c++