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

前端 未结 5 708
天涯浪人
天涯浪人 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:44

    The const qualifier means it will not change any members of the class.

    In this case rep is the only member of the class and I see no attempt to modify this member. Anything pointed at or referenced outside the class is not considered as part of the class.

    A solution to this problem would be to replace the char* with a std::string.
    Then you would only be able to call const members of std::string from within toUpper()

    For example (use std::string)

    class String
    {
        std::string rep;
    
        void toUpper() const
        { 
            for (int i = 0; rep [i]; i++)
                rep[i] = toupper(rep[i]);
    
            // Can only use const member functions on rep.
            // So here we use 'char const& std::string::operator[](size_t) const'
            // There is a non const version but we are not allowed to use it
            // because this method is const.
    
            // So the return type is 'char const&'
            // This can be used in the call to toupper()
            // But not on the lhs of the assignemnt statement
    
        }
    }
    

提交回复
热议问题