Gob*_*0st 8 c++ operator-overloading lvalue
为什么myint ++++可以用VS2008编译器和gcc 3.42编译器编译好?我期待编译器说需要左值,例子见下文.
struct MyInt
{
MyInt(int i):m_i(i){}
MyInt& operator++() //return reference, return a lvalue
{
m_i += 1;
return *this;
}
//operator++ need it's operand to be a modifiable lvalue
MyInt operator++(int)//return a copy, return a rvalue
{
MyInt tem(*this);
++(*this);
return tem;
}
int m_i;
};
int main()
{
//control: the buildin type int
int i(0);
++++i; //compile ok
//i++++; //compile error :'++' needs l-value, this is expected
//compare
MyInt myint(1);
++++myint;//compile ok
myint++++;//expecting compiler say need lvalue , but compiled fine !? why ??
}
Run Code Online (Sandbox Code Playgroud)
不,重载运算符不是运算符 - 它们是函数.因此GCC接受这一点是正确的.
myobj++++;等效于myobj.operator++(0).operator++(0);
允许在类类型的temprorary对象上Caling成员函数(包括重载的运算符).