为什么myClassObj ++++不会产生编译错误:'++'需要l-value就像buildin类型那样?

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)

Arm*_*yan 8

不,重载运算符不是运算符 - 它们是函数.因此GCC接受这一点是正确的.

myobj++++;等效于myobj.operator++(0).operator++(0); 允许在类类型的temprorary对象上Caling成员函数(包括重载的运算符).

  • 这是不正确的:重载运算符既是运算符**又是**函数.重要的一点是用户定义的运算符的*requirements*是运算符实现的运算符,它们可能因*实现它而有所不同.在这种特殊情况下作为成员函数. (2认同)