为什么myClassObj ++++不会导致编译错误:'++'需要l值,正如buildin类型吗? [英] Why myClassObj++++ doesn't incur a compile error : '++' needs l-value just as buildin type do?

查看:198
本文介绍了为什么myClassObj ++++不会导致编译错误:'++'需要l值,正如buildin类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么myint ++++编译良好与VS2008编译器和gcc 3.42编译器?我期待编译器说需要lvalue,例子见下面。

Why myint++++ compiles fine with VS2008 compiler and gcc 3.42 compiler ?? I was expecting compiler say need lvalue, example see below.

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 ??
}


推荐答案

运算符 - 它们是函数。因此GCC是正确的接受

No, overloaded operators are not operators - they're functions. So GCC is correct to accept that.

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

myobj++++; is equivalent to myobj.operator++(0).operator++(0); Caling a member function (including overloaded operator) on a temprorary object of class type is allowed.

这篇关于为什么myClassObj ++++不会导致编译错误:'++'需要l值,正如buildin类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆