C++ const 成员函数正在修改成员变量

发布于 2024-12-04 10:32:49 字数 349 浏览 1 评论 0原文

今天我发现这样的代码是有效的。这对我来说真的很奇怪,因为据我所知,你不能修改 const 成员函数中的任何成员。实际上你不能直接这样做,但你可以调用非常量成员函数。如果将成员函数标记为 const ,这意味着传递给函数的 this 指针指向 const 对象,那么在下面的示例中如何调用非 const 成员函数?

#include <iostream>

class X
{
public:
    void foo() const
    {
        ptr->bar();
    }
    void bar() {}
private:
    X * ptr;
};

int main()
{
}

Today I found out that code like that works. That sounds really strange to me, because as far as I always knew you can't modify any of members from const member function. You actually can't do it directly, but you can call non-const member function. if you mark member function as const that means that this pointer passed to the function is pointing to const object, then how non-const member function is called in the example bellow?

#include <iostream>

class X
{
public:
    void foo() const
    {
        ptr->bar();
    }
    void bar() {}
private:
    X * ptr;
};

int main()
{
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

狠疯拽 2024-12-11 10:32:49

你的成员变量不是X,而是指向X的指针。只要foo不修改指针,它就可以是const

Your member variable is not X, but pointer to X. As long as foo does not modify the pointer, it can be const.

家住魔仙堡 2024-12-11 10:32:49

当你有一个指针成员时,那么该指针在 const 方法中就是 const 。您将无法更改存储在指针中的地址。但你可以随心所欲地改变指尖。

更有趣的是,

X* const cannot_change_pointer;  //this is how top-level const applies to pointers
const X* cannot_change_pointee;

出于同样的原因,方法上的 const 对引用成员没有任何影响(const 方法只会阻止您引用其他无法通过引用完成的内容) )。

When you have a pointer member, then the pointer is const in a const method. You won't be allowed to change the address stored in the pointer. But you can change the pointee all you like.

It's the difference between

X* const cannot_change_pointer;  //this is how top-level const applies to pointers
const X* cannot_change_pointee;

What's even more interesting is that const on a method has no effect whatsoever on reference members for the same reason (a const method would only prevent you making a reference refer to something else which can't be done with a reference anyway).

半夏半凉 2024-12-11 10:32:49

这看起来完全没问题。对 foo 的调用不会修改 ptr 成员。因此, foo 的常量性受到尊重。

我的 2 美分

That's seems perfectly OK. The call to foo does not modify the ptr member. Hence, the constness of foo is respected.

my 2 cents

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文