为什么这个 const 成员函数允许修改成员变量? [英] Why does this const member function allow a member variable to be modified?

查看:12
本文介绍了为什么这个 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;
}

推荐答案

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

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

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

Your example does not mutate the member variables themselves.

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

A const on a member function, will ensure that you treat all of your member variables as const.

这意味着如果你有:

int x;
char c;
char *p;

那么你将拥有:

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

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

There are 2 types of const pointers. A const member function uses the one I've listed above.

获取所需错误的方法:

尝试改变:

char * rep;

到:

char rep[1024];

并删除这一行:

rep = new char [strlen(s)+1];

它会抛出你所期望的错误(由于 const 关键字不能修改成员)

It will throw the error you are expecting (can't modify members because of const keyword)

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

Because there is only 1 type of const array. And that means you cannot modify any of its data.

现在整个系统实际上被下面的例子破坏了:

Now the whole system is actually broken with the following example:

class String
{

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

 ...


 String :: String (const char* s)
 {
    rep = rep2;
    strcpy (rep, s); 
 }

所以这里要吸取的教训是成员函数上的 const 关键字并不能确保你的对象根本不会改变.

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

It only ensures that each member variable will be treated as const. And for pointers, there is a big diff between const char * and char * const.

大多数时候,一个 const 成员函数意味着该成员函数不会修改对象本身,但并非总是如此,如上例所示.

Most of the time a const member function will mean that the member function will not modify the object itself, but this is not always the case, as the above example shows.

这篇关于为什么这个 const 成员函数允许修改成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆