开发者

C++ : automatic const?

开发者 https://www.devze.com 2023-01-06 13:01 出处:网络
When I compile this code: class DecoratedString { private: std::string m_String; public: // ... constructs, destructors, etc

When I compile this code:

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

I get the following error from g++: invalid initialization of reference of type 'std::string&" from expression of type 'const std::string'.

Why is m_String being treated as const? Shouldn't the compiler simply create a reference here?

EDIT:

Further, what sho开发者_如何学运维uld I do to get this function to act as a conversion to a string that will work in most cases? I made the function const, as it doesn't modify the internal string... maybe I just need to make it return a copy...

EDIT: Okay... making it return a copy worked.


m_String is treated as const because it is accessed as

this->m_String

and this is const because the member function, ToString() is const-qualified.


m_String is const at that point because you've chosen to declare the method as const (which of course makes all data instance members const, too) -- if you need to bypass that for that specific data member, you could choose to explicitly make it mutable.


Because the method is const (the const in std::string& ToString() const). Const method see this as a const object, and its memebers as const objects, too.


Because you access m_String through a constant this (the method is const).

0

精彩评论

暂无评论...
验证码 换一张
取 消