2010-06-01 101 views
4

考慮以下類:問題訪問基地成員在派生構造

class Foo 
{ 
    struct BarBC 
    { 
    protected: 
     BarBC(uint32_t aKey) 
      : mKey(aKey) 
       mOtherKey(0) 

    public: 
     const uint32_t mKey; 
     const uint32_t mOtherKey; 
    }; 


    struct Bar : public BarBC 
    { 
     Bar(uint32_t aKey, uint32_t aOtherKey) 
      : BarBC(aKey), 
       mOtherKey(aOtherKey) // Compile error here 
    }; 
}; 

我得到該點處的編譯錯誤表示:

error: class `Foo::Bar' does not have any field named `mOtherKey'. 

任何人都可以解釋一下嗎?我懷疑這是一個語法問題,因爲我的Bar類是在Foo類中定義的,但似乎無法找到解決方法。

這是簡單的公共繼承,所以mOtherKey應該可以從Bar構造函數訪問。對?

或者它與mOtherKey是const並且我已經將它初始化爲0BarBC構造函數有關?

回答

8

您不能通過成員初始化程序列表初始化基類的成員,只能直接和虛擬基類以及類本身的非靜態數據成員。
其他參數傳遞給基類的構造函數來代替:

struct BarBC { 
    BarBC(uint32_t aKey, uint32_t otherKey = 0) 
     : mKey(aKey), mOtherKey(otherKey) 
    {} 
    // ... 
}; 

struct Bar : public BarBC { 
    Bar(uint32_t aKey, uint32_t aOtherKey) 
     : BarBC(aKey, aOtherKey) 
    {} 
}; 
+0

@George的參數附加BarBC構造 - 謝謝。我試圖默認初始化基類構造函數中的所有常量數據成員(以避免編譯錯誤),然後在派生構造函數中設置派生類特定成員(同時仍將成員留在基類中)。不是任何措施最好的階級結構。但我沒有意識到初始化列表有這樣的限制。 – LeopardSkinPillBoxHat 2010-06-01 06:28:14

1

你不能這樣做,因爲BarBC構建mOtherKey - 你不能覆蓋它。

你要麼指定新的價值:

Bar(...) : ... 
{ mOtherKey=aOtherKey; } 

,或者創建具有mOtherKey