返回“常量布尔值”会导致警告 C4180

Return of `const bool` causes warning C4180

本文关键字:警告 C4180 常量 布尔值 常量布尔值 返回      更新时间:2023-10-16
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;
    }
};

问题1>使用const Fundamental_Data_Types作为函数返回值真的没有意义吗?

问题2>使用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
}
是的

,对你的两个问题都是肯定的。 返回值为右值和 CV 限定符仅适用于具有类类型。

原因很简单:通常什么都没有你可以用一个右值来做常量会做出区别——毕竟它是一个值,而不是一个对象。对于类类型,有一些成员函数要纳入帐户(这意味着您可以从rvalue(,所以恒常性突然变得相关。