运算符重载

复制代码
#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;
}
相关推荐
pystraf6 分钟前
LG P9844 [ICPC 2021 Nanjing R] Paimon Segment Tree Solution
数据结构·c++·算法·线段树·洛谷
Funny-Boy23 分钟前
菱形继承原理
c++
Nobkins2 小时前
2021ICPC四川省赛个人补题ABDHKLM
开发语言·数据结构·c++·算法·图论
海棠蚀omo2 小时前
C++笔记-红黑树
开发语言·c++·笔记
一个Potato3 小时前
C++笔试题(金山科技新未来训练营):
c++·科技
休息一下接着来3 小时前
C++ I/O多路复用
linux·开发语言·c++
龙湾开发3 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 12.曲面细分
c++·笔记·学习·3d·图形渲染
darkchink4 小时前
[LevelDB]LevelDB版本管理的黑魔法-为什么能在不锁表的情况下管理数据?
c语言·数据库·c++·oracle·数据库开发·dba·db
易只轻松熊4 小时前
C++(23):容器类<vector>
开发语言·数据结构·c++
ha20428941944 小时前
c++学习之--- list
c语言·c++·学习·list