Ton*_*ark 12 c++ operator-overloading
我知道我可以在postfix 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;
}
Run Code Online (Sandbox Code Playgroud)
我期待着两者,t1.operator++(5)并且t1++5会以相同的方式工作。
Bat*_*eba 11
由于最大的munch规则,表达式
t1++x
Run Code Online (Sandbox Code Playgroud)
被解析为
t1 ++ x
Run Code Online (Sandbox Code Playgroud)
并分组为
(t1 ++) x
Run Code Online (Sandbox Code Playgroud)
这没有道理;宁可t1 x没有道理。
| 归档时间: |
|
| 查看次数: |
223 次 |
| 最近记录: |