以前经常看到诸如++i--++之类的C、Java题,那个时候是这样理解的:前缀式的++i是指先计算i然后整个++i融为一体返回i递增后的值,i++是先用i的原值完成正了八经的程序,什么都完事了之后再递增。下面通过C++中对自定义类型的递增操作,说明前缀式和后缀式的区别。
用C++封装int类
- class NewInt
- {
- public:
- NewInt():RootInt(0){};
- NewInt(int IniInt):RootInt(IniInt){};
- NewInt& operator++()
- {
- cout<<"prefix"<<endl;
- this->RootInt+=1;
- return *this;
- }
- NewInt operator++(int) //后缀,对参数(int)不要疑惑,int没有实质的作用,仅仅是为了区别前缀方式,标志这个++操作符是后缀形式
- {
- cout<<"postfix"<<endl;
- NewInt preNum = *this; //后缀递增操作中,先要保存原对象到一个对象中这里采用的前缀式中方法;
- ++(*this); //然后对原对象进行递增操作 ;
- return preNum; //最后返回原来保存的元对象。
- }
- private:
- int RootInt;
- };
调试代码:
- NewInt DBInt1(12) ;
- ++DBInt1; cout<<DBInt1.getRootInt()<<endl;
- cout<<"-----**------"<<endl;
- DBInt1++; cout<<DBInt1.getRootInt()<<endl;
程序输出:
- prefix
- 13
- -----**------
- postfix
- prefix
- 14
- Press any key to continue