重载++运算符 [英] Overload ++ operator
问题描述
我试图在第一次处理运算符重载,我写了这个代码重载++运算符增加类变量 i
和 x
by a ..
它执行的工作,但编译器显示这些警告:
I am trying to deal with operator overloading at the first time, and I wrote this code to overload ++ operator to increment class variables i
and x
by one..
It does the job but the compiler showed these warnings:
警告1警告C4620:没有为
找到'operator ++'的后缀形式类型'tclass',使用前缀
形式c:\users\ahmed\desktop\cppq\cppq\\ \\ cppq.cpp 25
Warning 1 warning C4620: no postfix form of 'operator ++' found for type 'tclass', using prefix form c:\users\ahmed\desktop\cppq\cppq\cppq.cpp 25
警告2警告C4620:没有为
找到'operator ++'的后缀形式类型'tclass',使用前缀
form c:\users\ahmed\desktop\cppq\cppq\cppq.cpp 26
Warning 2 warning C4620: no postfix form of 'operator ++' found for type 'tclass', using prefix form 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;
}
推荐答案
>
This syntax:
tclass operator++()
$ b b
用于前缀 ++
(实际上通常写为 tclass& operator ++()
)。要区分后缀增量,请添加一个未使用的 int
参数:
is for prefix ++
(which is actually normally written as tclass &operator++()
). To distinguish the postfix increment, you add a not-used int
argument:
tclass operator++(int)
c $ c> tclass& ,因为结果可能在之后使用:(++ rr).x
。
再次注意,后缀增量看起来像这样:
Again, note that the postfix increment looks like this:
tclass operator++(int)
{
tclass temp = *this;
++*this; // calls prefix operator ++
// or alternatively ::operator++(); it ++*this weirds you out!!
return temp;
}
这篇关于重载++运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!