2013-03-17 127 views
1

給定一個具有受保護成員的抽象基類,如何提供只讀派生類的讀取權限?如何讓派生類只讀成員?

爲了說明我的意圖,我提供了一個最簡單的例子。這是基礎類。

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構件。我怎樣才能產生預期的行爲?

+0

除了使它成爲一個常數,你不能。 – 2013-03-17 10:50:20

+2

你可以讓它私人,只是提供一個受保護的getter方法? – 2013-03-17 10:51:28

+1

您應該定義一個構造函數來初始化'Readonly'。 – 2013-03-17 10:54:26

回答

8

通常的方式做到這一點是讓你的會員private在基類中,並提供一個protected訪問:

class Base 
{ 
public: 
    virtual ~Base() = 0; 
    void Foo() 
    { 
     m_Readonly = 42; 
    } 
protected: 
    int Readonly() const { return m_Readonly; } 
private: 
    int m_Readonly; 
}; 
+0

比我的回答+1好多了。 – jrok 2013-03-17 10:52:54

+0

謝謝,有時它很簡單! – danijar 2013-03-17 10:53:29

+1

刪除'inline'關鍵字;它是通過在聲明中定義而「內聯」的。 – 2013-03-17 10:53:32

4

由於保護成員在派生類中可見,如果你想成員是在派生類中只讀,您可以將其設爲私有,並提供getter函數。

class Base { 
public: 
    Base(); 
    virtual Base(); 

    public: 
     int getValue() {return value;} 

    private: 
     int value; 
} 

這樣您仍然可以更改基類中的值,並且它只能在子類中進行讀取。

0

繼承的最佳實踐指導方針應該始終使成員變量保持私有,並將訪問者函數公開。如果你有隻需要派生類調用的公共函數,這意味着你正在編寫意大利麪代碼。 (來源:邁爾有效的C++項目22)

+0

那麼受保護的關鍵字是什麼? ;) – danijar 2014-01-14 08:23:12

相關問題