【发布时间】:2013-03-17 10:48:31
【问题描述】:
给定一个带有受保护成员的抽象基类,我怎样才能只提供对派生类的读取访问权限?
为了说明我的意图,我提供了一个最小的示例。这是基类。
class Base
{
public:
virtual ~Base() = 0;
void Foo()
{
Readonly = 42;
}
protected:
int Readonly; // insert the magic here
};
这是派生类。
class Derived : public Base
{
void Function()
{
cout << Readonly << endl; // this should work
Readonly = 43; // but this should fail
}
};
不幸的是,我不能使用const 成员,因为它必须可由基类修改。我怎样才能产生预期的行为?
【问题讨论】:
-
除了让它成为一个常数,你不能。
-
能否将其设为私有并仅提供受保护的 getter 方法?
-
你应该定义一个构造函数来初始化
Readonly。
标签: c++ inheritance readonly member