目录
递增运算符重载 前置++的效率略高于后置++,原因是前置不会调用拷贝构造
递减运算符重载
++和--对于默认数据类型编译器都知道该如何递增递减,但是对于自定义数据类型,编译器不知道该如何运算,于是需要用到重载。
递增运算符重载
1.前置++
class MyInter { public: MyInter() { this->m_Num = 0; } //重置前置++ MyInter& operator++() { //先++ m_Num++; //后返回 return *this; } private: int m_Num; };
2.后置++
class MyInter { public: friend ostream& operator<<(ostream& cout, MyInter& myInt); MyInter() { this->m_Num = 0; } //重置后置++ MyInter operator++(int) { //先返回 MyInter temp=*this; //后++ this->m_Num++; return temp; } private: int m_Num; };
递减运算符重载
1.前置--
class MyInter { public: MyInter() { this->m_Num = 0; } //重置前置-- MyInter& operator--() { //先-- m_Num--; //后返回 return *this; } private: int m_Num; };
2.后置--
class MyInter { public: MyInter() { this->m_Num = 0; } //重置后置-- MyInter operator--(int) { //先返回 MyInter temp=*this; //后-- this->m_Num--; return temp; } private: int m_Num; };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)