一、单目运算符的重载
单目运算符可分为两种:
1)可以放在前面,也可以放在后面的单目,如:++ --
2)只能放在前面的运算符:! +(正号) -(负号)& ~ ()
3)只能放到后面的运算符:* ->
重载单目运算符方法有两种: 类成员重载以及友元函数重载。
具体形式如下:

入参和返回值根据单目运算符的特性进行选择,导图只是一个通用形式,明白意思就行。
上代码:
- #include
- #include
- using namespace std;
-
- class Interger
- {
- public:
- Interger(int d=0):m_nData(d){}
-
- void operator--(int)
- {
- this->m_nData--;
- cout<
- cout << "operator--(int)"<< endl;
- }
-
- void operator++(int)
- {
- this->m_nData++;
- cout<
- cout << "operator++(int)"<< endl;
- }
-
- void operator++()
- {
- this->m_nData = this->m_nData+2;
- cout<
- cout << "operator++()"<< endl;
- }
-
- void show()
- {
- cout<
- }
- private:
- int m_nData;
- public:
- friend ostream& operator<<(ostream& os, Interger& input );
- friend Interger& operator!(Interger& input);
- };
-
-
- ostream& operator<<(ostream& os, Interger& input )
- {
- return os<
- }
-
- Interger& operator!(Interger& input)
- {
- input.m_nData = !input.m_nData;
- cout << "operator!()"<< endl;
- cout<< input.m_nData <
- return input;
- }
-
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
-
- Interger aa;
- aa--;
- ++aa;
- aa++;
-
- !aa;
-
- return a.exec();
- }
运行结果

二、运算符重载重载注意事项:
1,以下运算符不能重载
?: . :: sizeof && || & |
2,不能发明运算符
比如 @
3,不能改变运算符的特性,符合队形的运算属性。
4,不能重载基本类型的运算,重载时至少要有一个是类类型。
5,只能重载成全局运算符的运算符
第一个操作数是C++预定义类型 << >> ostream istream类型
第一个操作数是基本类型
6,只能重载成成员函数的运算符
1)=(+= -= *=) ---- 赋值运算符
2)[] ---------------数组对象(把对象当数组用)
3)() ----------------强转,函数对象(把对象当函数使用)
4)-> * -------------指针对象(把对象当指针使用)
-
相关阅读:
Python:实现quantum entanglement量子纠缠技术算法(附完整源码)
快速入门C++第四天——继承与派生
flink理论干货笔记(7)及spark论文相关思考
Spring原理:PostProcessor与AOP原理
【C++】函数重载 ① ( 函数重载概念 | 函数重载判断标准 - 参数个数 / 类型 / 顺序 | 返回值不是函数重载判定标准 )
Mybatis-plus中Service和Mapper
Linux vi和vim编辑器、快捷键的使用
CEAC之《企业信息管理》2
五、函数的调用过程
[kingbase运维之奇怪的现象]
-
原文地址:https://blog.csdn.net/yjj350418592/article/details/127978098