2014-02-23 57 views
4

爲什麼下面的工作就好了:如何用模板繼承一個類?

class a 
{ 
    public: 
    int n; 
}; 

class b : public a 
{ 
public: 
    b() 
    { 
     n = 1; 
    } 
}; 

int main() 
{ 
} 

但這不起作用:

template <class T> 
class a 
{ 
    public: 
     int n; 
}; 

template <class T> 
class b : public a<T> 
{ 
    public: 
    b() 
    { 
     n = 1; 
    } 
}; 

int main() 
{ 
} 

,並提供了以下錯誤:

1.cpp: In constructor ‘b<T>::b()’: 
1.cpp:14: error: ‘n’ was not declared in this scope 

,以及如何將一個繼承模板類,同時能夠使用其基本成員,並保持類型通用?

回答

3

你需要有資格爲「這個」或用「使用」指令(或明確與基類資格)。

簡而言之:該變量是,編譯器沒有尋找到一個依賴型(你一個< T>一個非依賴型(在模板類在T 非依賴的) )查找非依賴類型的聲明時

this->n,因爲「this」指的是一個依賴類,起作用。與我列出的其他方法一樣。


參考文獻:

常見問題在這裏:這裏http://www.parashift.com/c++-faq-lite/nondependent-name-lookup-members.html 活生生的例子:http://ideone.com/nsw4XJ