給定一個具有受保護成員的抽象基類,如何提供只讀派生類的讀取權限?如何讓派生類只讀成員?
爲了說明我的意圖,我提供了一個最簡單的例子。這是基礎類。
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