C++ const 成员函数正在修改成员变量
今天我发现这样的代码是有效的。这对我来说真的很奇怪,因为据我所知,你不能修改 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的成员变量不是
X
,而是指向X
的指针。只要foo
不修改指针,它就可以是const
。Your member variable is not
X
, but pointer toX
. As long asfoo
does not modify the pointer, it can beconst
.当你有一个指针成员时,那么该指针在 const 方法中就是 const 。您将无法更改存储在指针中的地址。但你可以随心所欲地改变指尖。
更有趣的是,
出于同样的原因,方法上的 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
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).
这看起来完全没问题。对 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