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

前端 未结 5 721
天涯浪人
天涯浪人 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 11:01

    toUpper() does not change the pointer (which belongs to the class). It only changes the data which rep points to (that do not belong to the class).

    However, 'const' is a sort of warranty for the users of your class: if a method is declared const, who uses an instance of your class can expect it won't change when calling the method. My point is, if toUpper() changes the state of a string, don't declare it const, whether C++ allows it or not.

提交回复
热议问题