如何避免前向声明错误?

时间:2017-11-04 04:37:52

标签: c++ class forward-declaration

我在C ++中获得了以下代码:

class Level;

class Node
{
  char letter;
  std::string path[2];
  Node *next;
  Level *nlevel;

  public:

    Node()
    {
      path[0] = "";
      path[1] = "";
      next = NULL;
      nlevel = NULL;
    }

    Node(char l, unsigned int h)
    {
      letter  = l;
      path[0] = "";
      path[1] = "";
      next = NULL;
      nlevel = NULL;
      nlevel->height = h;
    }

    virtual ~Node();
};

class Level
{
  std::list<Node> vnodes;
  unsigned int height;

  public:

    Level();
    virtual ~Level();
};

调用或声明类的正确方法是什么?我一直在阅读this并且我已经尝试在类Node之前放置class Level;但是我得到了一个前向声明错误,如果我将每个类分隔在另一个文件中以便稍后包含它我将会收到错误他们互相依赖,所以如何宣布他们呢?

2 个答案:

答案 0 :(得分:3)

只有在使用前向声明的类的指针时,才能转发声明。由于您在Level使用nlevel->height = h;的成员,因此您必须更改类的定义顺序。这样可行,因为Level只包含指向Node的指针。

由于heightLevel的私人成员,因此您还必须将friend class Node;添加到课程Level

   class Node;
   class Level
   {
       friend class Node;
       std::list<Node> vnodes;
       unsigned int height;

       public:

       Level();
       virtual ~Level();
   };

   class Node
   {
       char letter;
       std::string path[2];
       Node *next;
       Level *nlevel;

       public:

       Node()
       {   
           path[0] = ""; 
           path[1] = ""; 
           next = NULL;
           nlevel = NULL;
       }   

       Node(char l, unsigned int h)
       {
           letter  = l;
           path[0] = "";
           path[1] = "";
           next = NULL;
           nlevel = NULL;
           nlevel->height = h;
       }

       virtual ~Node();
   };

答案 1 :(得分:1)

解决此问题的方法是在Node的类定义之后放置Level 的函数定义,以便编译器提供完整的类型描述:

class Level;

class Node
{
  char letter;
  std::string path[2];
  Node *next;
  Level *nlevel;

  public:

    Node(); // put the definition after

    Node(char l, unsigned int h);

    virtual ~Node();
};

class Level
{
  std::list<Node> vnodes;
  unsigned int height;

  public:

    Level();
    virtual ~Level();
};

// put node's function definitions AFTER the definition of Level
Node::Node()
{
  path[0] = "";
  path[1] = "";
  next = NULL;
  nlevel = NULL;
}

Node::Node(char l, unsigned int h)
{
  letter  = l;
  path[0] = "";
  path[1] = "";
  next = NULL;
  nlevel = NULL;
  nlevel->height = h; // Now you have access problem
}

或者您可以将函数 definitions 移动到单独的.cpp源文件中。

现在您遇到了新问题,nlevel->height = h;正在尝试访问Level私有成员。