Aan*_*Aan 5 c++ operator-overloading
我试图在第一次处理运算符重载,并且我编写了这个代码来重载++运算符以增加类变量i和x一个..它完成了工作,但编译器显示了这些警告:
警告1警告C4620:找不到类型'tclass'的'operator ++'的后缀形式,使用前缀形式c:\ users\ahmed\desktop\cppq\cppq\cppq.cpp 25
警告2警告C4620:找不到类型'tclass'的'operator ++'的后缀形式,使用前缀形式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;
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*baz 12
这个语法:
tclass operator++()
Run Code Online (Sandbox Code Playgroud)
用于前缀++(实际上通常写为tclass &operator++()).要区分后缀增量,请添加一个未使用的int参数:
tclass operator++(int)
Run Code Online (Sandbox Code Playgroud)
另外,请注意前缀增量更好返回,tclass &因为结果可能在以下情况后使用:(++rr).x.
再次注意,后缀增量如下所示:
tclass operator++(int)
{
tclass temp = *this;
++*this; // calls prefix operator ++
// or alternatively ::operator++(); it ++*this weirds you out!!
return temp;
}
Run Code Online (Sandbox Code Playgroud)
有两个 ++ operator.你定义了一个并使用了另一个.
tclass& operator++(); //prototype for ++r;
tclass operator++(int); //prototype for r++;
Run Code Online (Sandbox Code Playgroud)
后增量和前增量有单独的重载.postincrement版本的签名是operator++(int),而preincrement的签名是operator++().
你定义了operator++(),所以你只定义了preincrement.但是,您在类的实例上使用postincrement,因此编译器会告诉您它将使用preincrement函数的调用,因为没有定义postincrement.