【问题标题】:Member from base class template not found [duplicate]未找到基类模板中的成员[重复]
【发布时间】: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-&gt;。我相信这是重复的。
  • 谢谢。我不知道我需要使用this-&gt;,所以我无法在重复的问题中找到很好的解释。

标签: c++ templates


【解决方案1】:

要使用模板基类中的成员,您必须以this-&gt; 为前缀。

template<typename T>
class Derived: public Base<T> {
public:
    T get() { return this->t; }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2018-08-20
    • 2014-08-01
    • 2016-04-06
    • 1970-01-01
    相关资源
    最近更新 更多