Why does this const member function allow a member variable to be modified?

前端 未结 5 707
天涯浪人
天涯浪人 2020-12-15 10:25
class String
{

    private:
        char* rep;

    public:
        String (const char*);
        void toUpper() const;
};


String :: String (const char* s)
{
             


        
5条回答
  •  臣服心动
    2020-12-15 10:57

    You cannot change the value of something declared as

    const char* rep;
    

    or

    const char* const rep;
    

    Unfortunately, declaring your member const turns into rep into

    char* const rep;
    

    which means, you cannot change the acutal address, but you can change the contents, whereas you cannot change the value.

    To make const memebrs respect keep your buffer const, you will need to make rep and array of characters or a string object rather than a character pointer.

提交回复
热议问题