运算符重载

复制代码
#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;
}
相关推荐
咩咦27 分钟前
C++学习笔记02:cin 和 cout 输入输出
c++·学习笔记·cin·输入输出·cout
咩咦32 分钟前
C++学习笔记05:引用和常引用
c++·学习笔记·引用·const·常引用
香蕉鼠片44 分钟前
算法过程中不会的
开发语言·c++
阿旭超级学得完1 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
li星野1 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
磊 子2 小时前
多态类原理+四种类型转换+异常处理
开发语言·c++·算法
王老师青少年编程2 小时前
csp信奥赛C++高频考点专项训练之字符串 --【回文字符串】:回文拼接
c++·字符串·csp·高频考点·信奥赛·字符串回文·回文拼接
Teleger3 小时前
在window上使用c++控制鼠标点击,实现的exe
c++·单片机·计算机外设
June`5 小时前
高并发内存池如何实现
c++·tcmalloc·内存池
ComputerInBook5 小时前
C++ 关键字 constexpr 和 consteval 之注意事项
开发语言·c++·constexpr·consteval