修改一个有关++运算符的C++程序

来源:百度知道 编辑:UC知道 时间:2024/06/19 08:20:11
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int a=1,b=1,c=1,d=1;
cout<<setw(8)<< "++(++a)" <<setw(8)<< ++(++a) <<setw(8)<< ";then a=" <<setw(8)<< a <<endl;
cout<<setw(8)<< "++(b++)" <<setw(8)<< ++(b++) <<setw(8)<< ";then b=" <<setw(8)<< b <<endl;
cout<<setw(8)<< "(++c)++" <<setw(8)<< (++c)++ <<setw(8)<< ";then c=" <<setw(8)<< c <<endl;
cout<<setw(8)<< "(d++)++" <<setw(8)<< (d++)++ <<setw(8)<< ";then d=" <<setw(8)<< d <<endl;
}

/*出错信息:
------ Build started: Project: 27, Configuration: Debug Win32 ------
Compiling...
27.cpp
.\27.cpp(8) : error C2105: '++' needs l

你用的是vc6.0吧,里面这两个++(b++) ,(d++)++ 是错误的,vc自己有些规则,你不需要深入研究这些,没有意义,只要知道这两个不对就行
如果你真想知道原因,我写出来
.前缀和后缀的operator ++ 有所不同,大致如下:

T & T::operator++() { // 这个是前缀的
// 这里实现 *this 增加 1 的概念
return *this;
}

const T T::operator++(int) { // 这个是后缀的
T t = *this;
// 这里实现 t 的增加 1 概念
return t; // 你看这里是一个临时变量
}

根据第二个方法可以看出,如果后缀方式多次加加,第二次开始作用不到最初的对象身上了,所以干脆禁止连续的++,使用const T作为返回类型。