假设我们有如下一段代码:
class Base {
public:
int a = 5;
};
class Derived : public Base {
public:
Base *parent_ = new Base;
Base* parent() const { return parent_; }
};
void f(const Derived *derived) {
Base *p = derived->parent();
p->a = 10; // <- is this correct?
}
我个人认为这里有一个问题:
In function
f
we take a pointer toconst
object of classDerived
. This makes each member of it alsoconst
thusparent_
becomesconst Base *
. If it is const we should not have an ability to modify the object on which the pointer points.
我哪里错了?
最佳答案
This makes each member of it also const thus
parent_
becomesconst Base *
.
不,指针本身会变成const,而不是它指向的对象。所以 parent_
变成了 Base * const
,而不是 const Base *
,你的代码是有效的。
关于c++ - 请澄清 const 限定符传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295656/