2012-12-09 65 views
5

說我有以下類:我可以在派生類中爲基類的成員別名嗎?

template <class T> 
class Base { 
    protected: 
    T theT; 
    // ... 
}; 

class Derived : protected Base <int>, protected Base <float> { 
    protected: 
    // ... 
    using theInt = Base<int>::theT;  // How do I accomplish this?? 
    using theFloat = Base<float>::theT; // How do I accomplish this?? 
}; 

在我的派生類,我想用一個更直觀的名稱,使得在派生類的更多意義上是指Base::theT。我正在使用GCC 4.7,它具有很好的C++ 11功能。有沒有使用using語句來完成這種我在上面的示例中嘗試過的方式?我知道在C++ 11中,using關鍵字可以用於別名類型以及例如。將受保護的基類成員納入公共範圍。有沒有類似的機制來混淆成員?

+4

我覺得你要麼需要引用,要麼可能是一個不會佔用派生類空間的函數。 :| – Xeo

+0

謝謝,參考工作。 –

回答

6

Xeo的小費工作。如果您正在使用C++ 11,你可以聲明別名,像這樣:

int &theInt = Base<int>::theT; 
float &theFloat = Base<float>::theT; 

如果沒有C++ 11,我想你也可以初始化它們在構造函數:

int &theInt; 
float &theFloat; 
// ... 
Derived() : theInt(Base<int>::theT), theFloat(Base<float>::theT) { 
    theInt = // some default 
    theFloat = // some default 
} 

編輯: 輕微的煩惱是,你不能初始化這些別名成員的值,直到構造函數的主體(即花括號內)。

+3

請注意,這會通過'sizeof(void *)'乘以引用數量來增加派生類的大小。這就是爲什麼我包含了一個名爲'theXXX'的簡單getter函數的建議。 – Xeo

+0

是的,我想你是對的。幸運的是,我不認爲額外的8個字節會殺死我,因爲我沒有很多Derived類的實例,所以當我訪問數據成員時,我可以堅持使用易於使用的參考版本。 –

相關問題