2011-01-26 100 views
1

我正在首次使用模板類,並試圖弄清楚爲什麼當我使用繼承時編譯器似乎不喜歡。C++繼承的模板類無權訪問基類

下面是代碼:

template <typename T> 
struct xPoint2 
{ 
    T x; 
    T y; 

    xPoint2() { x = 0; y = 0; }; 
}; 

template <typename T> 
struct xVector2 : xPoint2<T> 
{ 
    xVector2() { x = 0; y = 0; }; 
}; 

編譯器輸出:

vector2.hh: In constructor ‘xVector2<T>::xVector2()’: 
vector2.hh:11: error: ‘x’ was not declared in this scope 
vector2.hh:11: error: ‘y’ was not declared in this scope 

是沒可能以這種方式使用模板?

感謝

+1

考慮使用初始化而不是分配在類的構造函數。 – aschepler 2011-01-26 21:38:10

回答

4

你必須明確地提及父:

template <typename T> 
struct xVector2 : xPoint2<T> 
{ 
    typedef xPoint2<T> B; 
    xVector2() { B::x = 0; B::y = 0; }; 
};