一、单目运算符的重载
单目运算符可分为两种:
1)可以放在前面,也可以放在后面的单目,如:++ --
2)只能放在前面的运算符:! +(正号) -(负号)& ~ ()
3)只能放到后面的运算符:* ->
重载单目运算符方法有两种: 类成员重载以及友元函数重载。
具体形式如下:
入参和返回值根据单目运算符的特性进行选择,导图只是一个通用形式,明白意思就行。
上代码:
#include <QCoreApplication>
#include <iostream>
using namespace std;class Interger
{
public:Interger(int d=0):m_nData(d){}void operator--(int){this->m_nData--;cout<<m_nData<<endl;cout << "operator--(int)"<< endl;}void operator++(int){this->m_nData++;cout<<m_nData<<endl;cout << "operator++(int)"<< endl;}void operator++(){this->m_nData = this->m_nData+2;cout<<m_nData<<endl;cout << "operator++()"<< endl;}void show(){cout<<m_nData<<endl;}
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<<input.m_nData <<endl;
}Interger& operator!(Interger& input)
{input.m_nData = !input.m_nData;cout << "operator!()"<< endl;cout<< input.m_nData <<endl;return input;
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);Interger aa;aa--;++aa;aa++;!aa;();
}
运行结果
二、运算符重载重载注意事项:
1,以下运算符不能重载
?: . :: sizeof && || & |
2,不能发明运算符
比如 @
3,不能改变运算符的特性,符合队形的运算属性。
4,不能重载基本类型的运算,重载时至少要有一个是类类型。
5,只能重载成全局运算符的运算符
第一个操作数是C++预定义类型 << >> ostream istream类型
第一个操作数是基本类型
6,只能重载成成员函数的运算符
1)=(+= -= *=) ---- 赋值运算符
2)[] ---------------数组对象(把对象当数组用)
3)() ----------------强转,函数对象(把对象当函数使用)
4)-> * -------------指针对象(把对象当指针使用)
本文发布于:2024-02-02 10:21:54,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170684051543162.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |