C++运算符重载实现的过程,代码
- #include
-
- using namespace std;
-
- class fun
- {
- private:
- int num;
-
- public:
- fun(){}
- fun(int a):num(a){} //有参构造
-
- //定义显示函数
- void show()
- {
- cout<
- }
-
- //定义全局函数实现加法运算符重载
- friend const fun operator+(const fun &a,const fun &b);
-
- //成员函数实现减法运算符重载
- const fun operator-(const fun &a)const
- {
- fun c;
- c.num=this->num-a.num;
- return c;
- }
-
- //成员函数实现关系运算符的重载
- bool operator>(const fun &a)const
- {
- return this->num>a.num;
- }
-
- //成员函数实现赋值运算符的重载
- fun & operator=(const fun &a)
- {
- this->num=a.num;
- return *this;
- }
-
- //成员函数实现后自增运算符的重载
- fun operator++(int)
- {
- this->num++;
- return *this;
- }
-
-
- };
- const fun operator+(const fun &a,const fun &b)
- {
- fun c;
- c.num=a.num+b.num;
- return c;
- }
-
-
-
-
- int main()
- {
- fun a(101); //有参构造
- a.show(); //显示函数
- fun b(2); //有参构造
- fun c=a+b; //加法运算符
- fun d=a-b; //减法运算符
- a++; //后自增运算符
- if(a>b) //逻辑>运算符
- {
- cout<<"a>b"<
- }else
- {
- cout<<"a<
- }
- a.show();
- b.show();
- c.show();
- d.show();
-
- d=a; //赋值运算符
- d.show();
-
- return 0;
- }
运行结果

-
相关阅读:
vue-cli-service: command not found问题解决
【C语言刷LeetCode】687. 最长同值路径(M)
Linux C 多线程
一种基于深度学习(卷积神经网络CNN)的人脸识别算法-含Matlab代码
手写小程序摇树工具(六)——主包和子包依赖收集
Google Chrome如何同步书签
Gradle系列【4】Project对象
FPGA千兆网 UDP 网络视频传输,基于88E1518 PHY实现,提供工程和QT上位机源码加技术支持
架构师之路3. 富士康 - 再也不见
@Component注解的使用及解析
-
原文地址:https://blog.csdn.net/weixin_58469613/article/details/133519910