错误:限定符在类型x的绑定引用中下降到类型y的初始化器。

时间:2022-09-13 17:04:58

why does the following throw this error:

为什么会出现以下错误:

IntelliSense: qualifiers dropped in binding reference of type "string &" to initializer of type "const string"

智能感知:限定符在类型“字符串&”的绑定引用中下降,用于类型“const字符串”的初始化器。

.h

. h

class A
{
public:
    wstring& GetTitle() const;
private:
    wstring title;    
};

.cpp

. cpp

wstring& GetTitle() const
{
    return this->title;
}

If i remove the const word, it stops complaining, and yet i have never made any changes to the variable?

如果我删除了const单词,它就停止了抱怨,但是我从来没有对变量做过任何更改?

1 个解决方案

#1


5  

By returning a non-const reference to a member of your class, you are giving the caller access to the object as if it's non const. But GetTitle, being a const function, does not have the right to grant that access.

通过将非const引用返回给类中的成员,您就可以让调用者访问该对象,就像它是非const一样。但是GetTitle,作为一个const函数,没有授予访问权限的权利。

For example:

例如:

A a;
string& b = a.GetTitle(); // Allows control over original variable

#1


5  

By returning a non-const reference to a member of your class, you are giving the caller access to the object as if it's non const. But GetTitle, being a const function, does not have the right to grant that access.

通过将非const引用返回给类中的成员,您就可以让调用者访问该对象,就像它是非const一样。但是GetTitle,作为一个const函数,没有授予访问权限的权利。

For example:

例如:

A a;
string& b = a.GetTitle(); // Allows control over original variable