【问题标题】:How to declare an object of nested class present in base class如何声明基类中存在的嵌套类的对象
【发布时间】:2015-04-27 12:16:01
【问题描述】:

我有一个无法编译的 C++ 程序:

template <class T>
class Base
{
  protected:
   class BaseNode
    {
          public:
             int i;
 };
 protected:
    typedef void (*functionPointer)(const T &t, void *data);
    virtual void apply( const functionPointer fn,  void *data) const;
};

template <class T>
class Derived : public Base<T *>
{
  public:
    typedef void (*functionPointer)(const T *t, void *data);
    virtual void apply( const functionPointer fn,  void *data) const;
};

template <class T> void Derived<T>::apply(  const functionPointer fn,
                                                 void           *data) const
{
   BaseNode *node ;
}
int main()
{
 Derived<int > b;
}

当我尝试编译它时,我收到以下错误:

pankajk[]> g++ sample2.cpp
sample2.cpp: In member function 'virtual void Derived<T>::apply(void (*)(const T*, void*), void*) const':
sample2.cpp:26: error: 'BaseNode' was not declared in this scope
sample2.cpp:26: error: 'node' was not declared in this scope

我是模板概念的新手,无法弄清楚我做错了什么。

【问题讨论】:

  • 语法和措辞改进

标签: templates c++11 nested-class


【解决方案1】:

Base&lt;T *&gt; 是一个依赖基类,因此您需要使用显式范围和 typename 关键字:

template <class T> void Derived<T>::apply(const functionPointer fn,
                                                 void           *data) const
{
    typename Base<T *>::BaseNode* node;
//  ~~~~~~~^ ~~~~~~~~^          
}

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2020-04-12
    • 2015-07-29
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多