自加自减运算符重载
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自加自减运算符重载相关的知识,希望对你有一定的参考价值。
#include <iostream> using namespace std; class CDemo { private: int n; public: CDemo(int i = 0):n(i){} CDemo& operator++(); CDemo operator++(int); operator int() { return n; } friend CDemo& operator--(CDemo&); friend CDemo operator--(CDemo&, int); }; CDemo& CDemo::operator++() { n++; return *this; } CDemo CDemo::operator++(int k) { CDemo tmp(*this); n++; return tmp; } CDemo& operator--(CDemo& d) { d.n--; return d; } CDemo operator--(CDemo& d, int) { CDemo tmp(d); d.n--; return tmp; } int main(){ CDemo d(5); cout << (d++) << ","; //等价于 d.operator++(0); cout << d << ","; cout << (++d) << ","; //等价于 d.operator++(); cout << d << endl; cout << (d--) << ","; //等价于 operator--(d,0); cout << d << ","; cout << (--d) << ","; //等价于 operator--(d); cout << d << endl; return 0; }
以上是关于自加自减运算符重载的主要内容,如果未能解决你的问题,请参考以下文章