【发布时间】:2012-10-31 20:10:28
【问题描述】:
可能重复:
Why do I have to access template base class members through the this pointer?
我的类层次结构如下:
template<typename T>
class Base {
protected:
T t;
};
template<typename T>
class Derived: public Base<T> {
public:
T get() { return t; }
};
int main() {
Derived<int> d;
d.get();
}
问题是受保护的member variable t is not found in the Base class。编译器输出:
prog.cpp: In member function 'T Derived<T>::get()':
prog.cpp:10:22: error: 't' was not declared in this scope
这是正确的编译器行为还是只是编译器错误?如果是正确的,为什么会这样?最好的解决方法是什么?
使用完全限定名称有效,但似乎不必要地冗长:
T get() { return Base<T>::t; }
【问题讨论】:
-
你必须使用
this->。我相信这是重复的。 -
谢谢。我不知道我需要使用
this->,所以我无法在重复的问题中找到很好的解释。