2011-02-07 107 views
7

可能重複:
[常見問題]Why doesn't a derived template class have access to a base template class' identifiers? Problem with protected fields in base class in c++
cannot access data member in a class templateC++模板類和繼承

下面的代碼給我的編譯錯誤。哪裏不對?

struct Base { 
    int amount; 
}; 

template<class T> struct D1 : public Base { 
}; 

template<class T> 
struct D2 : D1<T> { 
    void foo() { amount=amount*2; /* I am trying to access base class data member */ }; 
}; 

int main() { 
    D2<int> data; 
}; 


test.cpp: In member function 'void D2<T>::foo()': 
test.cpp:11: error: 'amount' was not declared in this scope 

如何解決這個問題?

感謝

+0

我以前見過這個問題幾次,但我找不到鏈接。 –

+0

發現一個,但如果有人可以找到一個更好的問題,會很好:[在C++中的基類中的保護字段的問題](http://stackoverflow.com/questions/1813671/problem-with-protected-字段在基類在C) –

+2

@Chris:這是一個[重複](http://stackoverflow.com/questions/4210108/cannot-access-data-member-in-a-class-template) ,這裏是一個[冗長的解釋](http://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-指針)。 – GManNickG

回答

8

這裏的問題有名稱如何從模板基類繼承的模板類擡頭做。背後的實際規則非常神祕,我不知道他們在我頭頂;我通常必須諮詢參考,以瞭解爲什麼這不起作用。

解決這個問題的方法是顯式前綴的會員,您正在使用this->訪問:

void foo() { 
    this->amount = this->amount * 2; // Or: this->amount *= 2; 
} 

這使編譯器在哪裏名字amount來源和應該解決的編譯器錯誤的明確提示。

如果有人想給出一個更詳細的描述爲什麼發生這個錯誤,我很樂意看到一個很好的解釋。

+1

錯誤的原因在於,如果基類的部分特化不包含這些成員中的某些成員,則編譯器不會對模板基類成員做任何假設。 – Gorpik

+0

謝謝。有用! – anon

+0

根據[這](http://www.hackcraft.net/cpp/templateInheritance/): 「需要注意基礎一個有趣的事情是,沒有它的成員函數創建後才類型T是。」所以編譯器在定義時可能不知道任何成員,而不僅僅是函數。 – jswolf19