C++:自动const?

J. *_*fer 2 c++ const-correctness

当我编译这段代码时:

class DecoratedString
{
private:
    std::string m_String;
public:
     // ... constructs, destructors, etc
     std::string& ToString() const
     {
         return m_String;
     }
}
Run Code Online (Sandbox Code Playgroud)

我从g ++中得到以下错误:invalid initialization of reference of type 'std::string&" from expression of type 'const std::string'.

为什么m_String被视为const?编译器不应该只是在这里创建引用吗?

编辑:

此外,我应该怎么做才能使这个函数作为一个字符串的转换,在大多数情况下将起作用? 我做了函数const,因为它不修改内部字符串...也许我只需要让它返回一个副本...

编辑:好的......让它返回一份副本.

Jam*_*lis 9

m_String 被视为const,因为它被访问为

this->m_String
Run Code Online (Sandbox Code Playgroud)

并且this是const因为成员函数ToString()是const限定的.