//例二 //程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> using namespace std; class Test { public: Test(int a=0) { Test::a = a; } Test& operator ++ (); Test operator ++ (int); public: int a; }; Test& Test::operator ++ ()//前递增 { this->a++; return *this; } Test Test::operator ++ (int)//后递增 { Test rtemp(*this);//这里会调用拷贝构造函数进行对象的复制工作 this->a++; return rtemp; } int main() { Test a(100); ++(++a); cout<<a.a<<endl; cout<<"观察后递增情况下临时存储对象的值状态:"<<(a++).a<<endl;//这里正是体现后递增操作先返回原有对象值地方 cout<<a.a<<endl; (a++)++; cout<<a.a<<endl;//由于后递增是值返回状态,所以(a++)++只对a做了一次递增操作,操作后为104而非105。 system("pause"); }
通过对前后递增运算的分析,我们可以进一步可以了解到,对于相同情况的单目运算符重载我们都必须做好这些区别工作,保证重载后的运算符符合要求。
|