#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;
}
运算符重载
曾钰芝2023-10-04 3:08
相关推荐
旖旎夜光几秒前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解Escalating_xu11 分钟前
【C++类和对象(上)】从类的定义、封装与对象模型到内存对齐和 this 指针吃着火锅x唱着歌14 分钟前
Effective C++ 学习笔记 条款45 运用成员函数模板接受所有兼容类型爱和冰阔落26 分钟前
【Linux】多线程打印为什么会乱?pthread 创建、等待、退出、取消与分离全实战luj_176829 分钟前
尾椎藏今生记忆?骨盆对应不确定性断点之下40 分钟前
C++类和对象:六个默认成员函数详解库玛西3 小时前
深入浅出传输层:UDP 与 TCP 协议全景指南Chester_19999 小时前
CSP202203C.计算资源调度器会周易的程序员10 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计小灰灰搞电子11 小时前
完全驾驭 Qt 与数据库:C++ ORM 框架 QxOrm 原理与实践指南