N-ary Tree实现:无法转换' Tree :: node *'到节点*'在任务中

时间:2015-10-09 20:59:20

标签: c++ pointers struct tree mingw

我正在尝试使用指针实现一个带有列表列表的n-ary树,这是我对Tree的实现:

class Tree{
public:

struct nodeSon{
    struct node* node_ptr;
    nodeSon* nextNodeSon_ptr;
};

struct node{
    char label;
    node* nextNode_ptr;
    struct nodeSon* nSon;
};

node* root;

void AddSon(int i, node n, char l); //Adds a son with label l to n at i position
};

当我尝试实施Tree::AddSon()时会出现问题:

void Tree::AddSon(int i, nodo n, char l){

node* nextPtr = root->nextNode_ptr;
node* newNode = new node();
newNode->label= l;
root->nextNode_ptr = newNode;
newNode->nextNode_ptr = nextPtr;

node* it = root;
while (it != &n) {
    it = it->nextNode_ptr;
}

nodeSon* it2 = it->nSon;
int counter = 1;
while (contador != i) {
    it2 = it2->sigNodoHijo_ptr;
}
nodeSon* nextPtrNH = it2->nextNodeSon_ptr;
nodeSon* newNodeNH = new nodeSon();
newNodeNH->node_ptr = newNodo; //error indication at this line
it2 = newNodeNH;
newNodoNH->nextNodeSon_ptr = nextPtrNH;
.
.
.
}

我尝试构建它时收到此错误:

Tree.cpp:110:27: error: cannot convert 'Tree::node*' to 'node*' in assignment
  • 为什么会这样?
  • 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

问题

class Tree{
  public:

    struct nodeSon{
      struct node* node_ptr;    // (1)
      nodeSon* nextNodeSon_ptr;
    };
};

(1),您基本上告诉编译器node_ptr应指向您尚未定义的类型,但此类型的定义将在以后提供。

问题在于编译器不能假设此类型位于class Tree内 - 因为您没有说过这种情况 - 而是假设struct node指的是< em> global namespace。

当您稍后在node内声明名为class Tree的类型时,已经太晚了; Tree::nodeSon::node_ptr的类型不会因为更多(从我们的角度来看)合适的类型而变化。

实施例

我们可以使用以下大大减少的测试用例重现您的错误。

struct A {
  struct B {
    struct C * ptr;
  };

  struct C { };
};
struct C { };
int main () {
  A::B x;
  A::C y;
  C    z;

  x.ptr = &y; // error,  `y` is of type `A::c`
  x.ptr = &z; // ok,     `z` is of type `::C`
}

解决方案

在编写node的定义之前,您需要告诉编译器在Tree中存在一个名为Tree::nodeSon的类型,通过前向声明它。

class Tree{
  public:
    struct node; // forward-declare Tree::node

    struct nodeSon{
      struct node* node_ptr;
      nodeSon* nextNodeSon_ptr;
    };

    struct node{
      char label;
      node* nextNode_ptr;
      struct nodeSon* nSon;
    };

    node* root;

    void AddSon (int i, node n, char l); //Adds a son with label l to n at i position
};