为什么这个const成员函数允许修改成员变量?

mah*_*esh 10 c++ const

class String
{

    private:
        char* rep;

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


String :: String (const char* s)
{
    rep = new char [strlen(s)+1];
    strcpy (rep, s);
}


void String :: toUpper () const
{
    for (int i = 0; rep [i]; i++)
    rep[i] = toupper(rep[i]);
}


int main ()
{
    const String lower ("lower");
    lower.toUpper();

    cout << lower << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ndy 20

const成员函数是一个不会改变其成员变量的成员函数.

成员函数上的const并不意味着const char*.这意味着您无法更改指针所包含的地址中的数据.

您的示例不会改变成员变量本身.

成员函数上的const将确保将所有成员变量视为const.

这意味着如果你有:

int x;
char c;
char *p;
Run Code Online (Sandbox Code Playgroud)

然后你将有:

const int x;
const char c;
char * const p; //<-- means you cannot change what p points to, but you can change the data p points to
Run Code Online (Sandbox Code Playgroud)

有两种类型的const指针.const成员函数使用我上面列出的那个.


一种获取所需错误的方法:

尝试改变:

char * rep;
Run Code Online (Sandbox Code Playgroud)

至:

char rep[1024];
Run Code Online (Sandbox Code Playgroud)

并删除此行:

rep = new char [strlen(s)+1];
Run Code Online (Sandbox Code Playgroud)

它会抛出你期望的错误(因为const关键字而无法修改成员)

因为只有一种类型的const数组.这意味着您无法修改任何数据.


现在整个系统实际上已经破坏了以下示例:

class String
{

    private:
        char rep2[1024];
        char* rep;

 ...


 String :: String (const char* s)
 {
    rep = rep2;
    strcpy (rep, s); 
 }
Run Code Online (Sandbox Code Playgroud)

因此,这里要学习的教训是,成员函数上的const关键字不能确保您的对象根本不会发生变化.

它只确保将每个成员变量视为const.对于指针,const char*和char*const之间存在很大差异.

大多数情况下,const成员函数意味着成员函数不会修改对象本身,但并非总是如此,如上例所示.