错误:限定符在类型x的绑定引用中删除到类型为y的初始化程序

Jim*_*988 10 c++

为什么以下抛出此错误:

IntelliSense:限定符在"string&"类型的绑定引用中删除到"const string"类型的初始化程序

.H

class A
{
public:
    wstring& GetTitle() const;
private:
    wstring title;    
};
Run Code Online (Sandbox Code Playgroud)

的.cpp

wstring& GetTitle() const
{
    return this->title;
}
Run Code Online (Sandbox Code Playgroud)

如果我删除const字,它会停止抱怨,但我从未对变量进行任何更改?

Ben*_*ley 11

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

例如:

A a;
string& b = a.GetTitle(); // Allows control over original variable
Run Code Online (Sandbox Code Playgroud)

  • @Cinch:可能是.但不是你联系的问题.仅仅因为错误信息是相同的,并不意味着问题是.这个涉及const成员函数,虽然连接可能对你或我来说很明显,但它不适合初学者. (3认同)