如果class B
总是*a
作为一个const
对象使用,那么正如其他人所说,只需将声明更改为
public: const A* a
在这一点上,我应该提一下, 的常量B::Func2
是一条红鲱鱼,因为它与 的常量完全没有关系B::a
。这意味着不允许更改 ; 的B::Func2
值。但是,允许取消引用和改变结果对象。const
a
a
现在,如果相对于class B
两者都有操作const
和非const
操作,*a
那么您的类设计需要更改。class B
如果您切换到使用上面的 a会更好const A* a
,并添加另一个class D : public B
封装所有变异操作的方法。另外,a
应该隐藏在一个属性设置器后面;这使您可以执行以下操作
class B {
const A* a;
public:
void setA(const A* a) { this->a = a; }
void Func2() const {}
};
class D : public B {
A* a;
public:
using B::setA;
void setA(A* a) {
this->a = a;
static_cast<B*>(this)->setA(const_cast<const A*>(a));
}
void Func3() { /* do something to D::a */ }
};
With this scheme both B
and D
keep independent, suitably typed pointers to the object to be accessed. If setA
is called on a B
, or on a D
with a const A*
parameter then only B::a
is set. If setA
is called on a D
with an A*
, then both B::a
and D::a
are properly set. This has become possible because by abstracting the member behind a setter you can then overload the setter on the constness of its parameter.