【发布时间】:2019-06-04 08:29:38
【问题描述】:
我知道我可以在后缀运算符 ++ 中使用虚拟 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 会以相同的方式工作。
【问题讨论】:
-
后缀
++(和--)的参数是一个hack(或聪明的解决方法,取决于你的观点),它被引入只是为了允许前缀和后缀的重载运营商。你不应该将它用于任何事情。 -
我的猜测是,现在,如果重新设计是可能的,那么它将通过标签类型参数而不是不明显的 int 重载来区分,例如重载
MyClass& operator++(std::prefix_t)与MyClass operator++(std::postfix_t)