运算符重载

复制代码
#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;
}
相关推荐
tan180°3 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
彭祥.5 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
lzb_kkk5 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
胖大和尚7 小时前
clang 编译器怎么查看在编译过程中做了哪些优化
c++·clang
钱彬 (Qian Bin)8 小时前
一文掌握Qt Quick数字图像处理项目开发(基于Qt 6.9 C++和QML,代码开源)
c++·开源·qml·qt quick·qt6.9·数字图像处理项目·美观界面
双叶8368 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++
源代码•宸9 小时前
C++高频知识点(二)
开发语言·c++·经验分享
jyan_敬言10 小时前
【C++】string类(二)相关接口介绍及其使用
android·开发语言·c++·青少年编程·visual studio
liulilittle10 小时前
SNIProxy 轻量级匿名CDN代理架构与实现
开发语言·网络·c++·网关·架构·cdn·通信
tan77º11 小时前
【Linux网络编程】Socket - UDP
linux·服务器·网络·c++·udp