我正在尝试第一次处理运算符重载,并且我编写了这个代码来重载++运算符以将类变量i
和x
递增一个..
它完成了这项工作,但编译器显示了这些警告:
警告1警告C4620:找不到'operator ++'的后缀形式 输入'tclass',使用前缀 表格c:\ users \ ahmed \ desktop \ cppq \ cppq \ cppq.cpp 25
警告2警告C4620:找不到'operator ++'的后缀形式 输入'tclass',使用前缀 表格c:\ users \ ahmed \ desktop \ cppq \ cppq \ cppq.cpp 26
这是我的代码:
class tclass{
public:
int i,x;
tclass(int dd,int d){
i=dd;
x=d;
}
tclass operator++(){
i++;
x++;
return *this;
}
};
int main() {
tclass rr(3,3);
rr++;
rr++;
cout<<rr.x<<" "<<rr.i<<endl;
system("pause");
return 0;
}
答案 0 :(得分:12)
此语法:
tclass operator++()
用于前缀++
(实际上通常写为tclass &operator++()
)。要区分后缀增量,请添加一个未使用的int
参数:
tclass operator++(int)
另请注意,前缀增量最好返回tclass &
,因为结果可能会在(++rr).x
之后使用。
再次注意,后缀增量如下所示:
tclass operator++(int)
{
tclass temp = *this;
++*this; // calls prefix operator ++
// or alternatively ::operator++(); it ++*this weirds you out!!
return temp;
}
答案 1 :(得分:6)
有两个 ++ operator
。你定义了一个并使用了另一个。
tclass& operator++(); //prototype for ++r;
tclass operator++(int); //prototype for r++;
答案 2 :(得分:5)
后增量和前增量有单独的重载。 postincrement版本的签名为operator++(int)
,而preincrement的签名为operator++()
。
您已定义operator++()
,因此您只定义了preincrement。但是,您在类的实例上使用postincrement,因此编译器会告诉您它将使用preincrement函数调用,因为没有定义postincrement。