为什么以下抛出此错误:
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)