运算符重载

复制代码
#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;
}
相关推荐
老猿讲编程30 分钟前
汽车车载软件平台化项目规模颗粒度选择的一些探讨
c++·汽车
clock的时钟1 小时前
c++第七天--继承与派生
开发语言·c++
John_ToDebug1 小时前
Chrome 浏览器前端与客户端双向通信实战
前端·c++·chrome
scoone1 小时前
ESP32开发中Kconfig ninja cmake 三者之间的关系
c++
Smile丶凉轩2 小时前
技术栈RabbitMq的介绍和使用
c++·分布式·rabbitmq
点云SLAM2 小时前
C++中string流知识详解和示例
开发语言·c++·istringstream·ostringstream·c++学习·stringstream·数据流操作
achene_ql9 小时前
select、poll、epoll 与 Reactor 模式
linux·服务器·网络·c++
SY师弟11 小时前
51单片机——计分器
c语言·c++·单片机·嵌入式硬件·51单片机·嵌入式
豪斯有话说12 小时前
C++_哈希表
数据结构·c++·散列表
real_metrix13 小时前
【学习笔记】erase 删除顺序迭代器后迭代器失效的解决方案
c++·迭代器·迭代器失效·erase