【问题标题】:ISO C++ forbids declaration of ‘Node’ with no typeISO C++ 禁止声明没有类型的“节点”
【发布时间】:2011-03-10 16:19:07
【问题描述】:

我正在移植在 RHEL 5.0 上在 linux 3 下编译的项目,因此使用 gcc 编译器版本 4.1.1。 我在一行上遇到了这个错误:

inline Tree<ExpressionOper< T > >::Node* getRootNode() const throw() { return m_rootPtr; }

按照顶部包含的tree.h,其中是类的模板声明:

template <typename T>
class Tree
{
public:
class Node
  {
  public:

    Node ()
      : _parent (NULL) {};

    explicit Node (T t)
      : _parent (NULL)
      , _data (t) {};

    Node (T t, Node* parent)
      : _parent (parent)
      , _data (t) {}; 

    ~Node()
    {
      for (int i = 0; i < num_children(); i++){
        delete ( _children [ i ] );
      }
    }; 

    inline T& data()
    {  
      return ( _data);          
    };  

    inline int num_children() const 
    {  
      return ( _children.size() );    
    };

    inline Node* child (int i)
    {
      return ( _children [ i ] );    
    };


    inline Node* operator[](int i)
    {  
      return ( _children [ i ] );    
    };

    inline Node* parent()
    {
      return ( _parent);
    };

    inline void set_parent (Node* parent)
    {
      _parent = parent;
    };

    inline bool has_children() const
    {
      return ( num_children() > 0 );
    };

    void add_child (Node* child)
    {
      child -> set_parent ( this );
      _children.push_back ( child );
    };

  private:
    typedef std::vector <Node* > Children;
    Children  _children;
    Node*     _parent;
    T         _data;

  }; 

非常感谢。

【问题讨论】:

    标签: c++ compiler-errors


    【解决方案1】:

    尝试以下操作,并阅读this

    inline typename Tree<ExpressionOper< T > >::Node* getRootNode() const throw()
    {
        return m_rootPtr;
    }
    

    简而言之,由于ExpressionOper&lt;T&gt; 是一个模板类型,在解析阶段编译器并不真正知道Tree&lt;ExpressionOper&lt;T&gt; &gt; 的内容是什么(直到它知道T)。因此,它不知道Tree&lt;ExpressionOper&lt;T&gt; &gt;::Node。您使用typename 关键字向编译器提示您的意思是类型,然后解析可以成功。符号查找发生在编译过程的后期。

    你得到的具体错误是编译器的一个怪癖:因为它没有设法注意到你有一个类型,它接下来假设你试图声明一个变量称为“节点”在命名空间或类Tree&lt;ExpressionOper&lt; T &gt; &gt; 中,当然如果你一直这样做,那么你会错过它的类型。

    【讨论】:

    • 啊哈哈 - 你刚到那里...不过更好的解释!
    【解决方案2】:

    也许你需要使用 typename 关键字:

    inline typename Tree<ExpressionOper< T > >::Node* etc...
    

    【讨论】:

      猜你喜欢
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多