我知道我可以在后缀 operator++ 中使用虚拟 int 作为 someClassObject.operator++(5)
,但为什么不能像 someClassObject++5
那样使用它?我问这个是因为 operator+
可以像 someClassObject1 + someClassObject2
一样使用。
{
public:
test(int x, string y) : x(x), y(y){}
test() :x(0), y("") {};
//skiping some code for copy constructor and assignment operator overload
test operator++(int x)
{
test a(*this);
a.x += x;
++(*this);
return a;
}
friend ostream& operator<<(ostream& ost, const test& test)
{
ost << test.x << " , " << test.y;
return ost;
}
int x;
string y;
};
int main()
{
test t1(5, "testing");
int x = 10;
cout << t1.operator++(x) << endl;
//the above line of code works but the line below gives error.
t1++x;
return 0;
}
我希望 t1.operator++(5)
和 t1++5
都能以相同的方式工作。
最佳答案
由于最大咀嚼规则,表达式
t1++x
被解析为
t1 ++ x
和分组为
(t1 ++) x
这毫无意义;而像 t1 x
是没有意义的。
关于c++ - 为什么我不能像 someClassObject++5 那样在后缀 operator++ 中使用虚拟参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56440118/