問(wèn)題描述
為什么 C++ 編譯器不能識(shí)別 g()
和 b
是 Superclass
的繼承成員,如以下代碼所示:
Why can't a C++ compiler recognize that g()
and b
are inherited members of Superclass
as seen in this code:
template<typename T> struct Superclass {
protected:
int b;
void g() {}
};
template<typename T> struct Subclass : public Superclass<T> {
void f() {
g(); // compiler error: uncategorized
b = 3; // compiler error: unrecognized
}
};
如果我簡(jiǎn)化 Subclass
并且只是從 Subclass
繼承然后它編譯.當(dāng)將 g()
完全限定為 Superclass
和 Superclass
時(shí),它也會(huì)編譯.我使用的是 LLVM GCC 4.2.
If I simplify Subclass
and just inherit from Subclass<int>
then it compiles. It also compiles when fully qualifying g()
as Superclass<T>::g()
and Superclass<T>::b
. I'm using LLVM GCC 4.2.
注意:如果我在超類中公開(kāi) g()
和 b
,它仍然會(huì)失敗并出現(xiàn)相同的錯(cuò)誤.
Note: If I make g()
and b
public in the superclass it still fails with same error.
推薦答案
這可以通過(guò)使用 using
將名稱拉入當(dāng)前范圍來(lái)修改:
This can be amended by pulling the names into the current scope using using
:
template<typename T> struct Subclass : public Superclass<T> {
using Superclass<T>::b;
using Superclass<T>::g;
void f() {
g();
b = 3;
}
};
或者通過(guò)this
指針訪問(wèn)來(lái)限定名稱:
Or by qualifying the name via the this
pointer access:
template<typename T> struct Subclass : public Superclass<T> {
void f() {
this->g();
this->b = 3;
}
};
或者,正如您已經(jīng)注意到的,通過(guò)限定全名.
Or, as you’ve already noticed, by qualifying the full name.
之所以有必要這樣做,是因?yàn)?C++ 不考慮用于名稱解析的超類模板(因?yàn)樗鼈兪菑膶倜Q并且不考慮從屬名稱).它在您使用 Superclass
時(shí)有效,因?yàn)樗皇悄0?它是模板的實(shí)例化),因此它的嵌套名稱不依賴 名字.
The reason why this is necessary is that C++ doesn’t consider superclass templates for name resolution (because then they are dependent names and dependent names are not considered). It works when you use Superclass<int>
because that’s not a template (it’s an instantiation of a template) and thus its nested names are not dependent names.
這篇關(guān)于使用模板訪問(wèn) C++ 中超類的受保護(hù)成員的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!