给定一个具有受保护成员的抽象基类,如何提供只读派生类的读取权限?如何让派生类只读成员?
为了说明我的意图,我提供了一个最简单的例子。这是基础类。
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
构件。我怎样才能产生预期的行为?
除了使它成为一个常数,你不能。 – 2013-03-17 10:50:20
你可以让它私人,只是提供一个受保护的getter方法? – 2013-03-17 10:51:28
您应该定义一个构造函数来初始化'Readonly'。 – 2013-03-17 10:54:26