6
struct CCompare
{
    const bool operator()(const int& lhs, const int& rhs) const {
        return lhs < rhs;
    }
};

警告 1 警告 C4180:应用于函数类型的限定符没有意义;

const bool我在编程书中看到了返回值的用法。当我用vs2010编译上面的代码时,它报告了警告C4180。

相反,以下代码不会导致相同的警告。

struct CCompare
{
    bool operator()(const int& lhs, const int& rhs) const {
        return lhs < rhs;
    }
};

Question1 > const Fundamental_Data_Typesas a function返回值的使用真的没有意义吗?

Question2 > 的用法是真的吗const Type仅当类型是类/结构时,作为函数返回值的使用才有意义吗?

谢谢

// 更新 //

struct CClass
{
    int val;
    CClass(int _val) : val(_val) {}

    void SetValue(int _val) {
        val = _val;
    }
};

struct CCompare
{
    const CClass getMe() const {
        return CClass(10);
    }

    CClass getMeB() const {
        return CClass(10);
    }
};

int main(/*int argc, char *argv[]*/) 
{
    CCompare c;

    c.getMe().SetValue(20);   // error
    c.getMeB().SetValue(20);  // ok
}
4

1 回答 1

7

是的,是的,你的两个问题。返回值是右值,而 cv 限定符仅适用于具有类类型的右值。

这样做的原因很简单:通常你不能用 rvalue 做任何事情,因为 const-ness 会产生影响——毕竟它是一个值,而不是一个对象。对于类类型,需要考虑成员函数(这意味着您可以从右值中获取左值),因此 const-ness 突然变得相关。

于 2013-07-08T14:41:19.187 回答