【发布时间】:2011-04-29 22:40:41
【问题描述】:
为什么 C++ 编译器不能识别 g() 和 b 是 Superclass 的继承成员,如下代码所示:
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<int> 继承,那么它会编译。当将 g() 完全限定为 Superclass<T>::g() 和 Superclass<T>::b 时,它也会编译。我正在使用 LLVM GCC 4.2。
注意:如果我在超类中将 g() 和 b 设为 public,它仍然会失败并出现同样的错误。
【问题讨论】:
-
发生这种情况是因为两阶段名称查找(并非所有编译器都默认使用)。这个问题有4个解决方案:1)使用前缀
Superclass<T>::b和Superclass<T>::g(),2)使用前缀this->a和this->g(),3) 添加语句using Superclass<T>::a和using Superclass<T>::g,4) 使用启用许可模式的全局编译器开关。这些解决方案的优缺点在stackoverflow.com/questions/50321788/… 中进行了描述
标签: c++ templates inheritance