問題描述
為什么 C++ 編譯器不能識別 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
}
};
如果我簡化 Subclass
并且只是從 Subclass
繼承然后它編譯.當將 g()
完全限定為 Superclass
和 Superclass
時,它也會編譯.我使用的是 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.
注意:如果我在超類中公開 g()
和 b
,它仍然會失敗并出現相同的錯誤.
Note: If I make g()
and b
public in the superclass it still fails with same error.
推薦答案
這可以通過使用 using
將名稱拉入當前范圍來修改:
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;
}
};
或者通過this
指針訪問來限定名稱:
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;
}
};
或者,正如您已經注意到的,通過限定全名.
Or, as you’ve already noticed, by qualifying the full name.
之所以有必要這樣做,是因為 C++ 不考慮用于名稱解析的超類模板(因為它們是從屬名稱并且不考慮從屬名稱).它在您使用 Superclass
時有效,因為它不是模板(它是模板的實例化),因此它的嵌套名稱不依賴 名字.
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.
這篇關于使用模板訪問 C++ 中超類的受保護成員的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!