【问题标题】:N-ary Tree implementation: cannot convert 'Tree::node*' to 'node*' in assignmentN-ary Tree 实现:无法在分配中将 'Tree::node*' 转换为 'node*'
【发布时间】:2015-10-09 20:59:20
【问题描述】:

我正在尝试用指针实现的列表列表创建一个 n 叉树,这是我的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

  • 为什么会这样?
  • 我该如何解决这个问题?

【问题讨论】:

    标签: c++ pointers struct tree mingw


    【解决方案1】:

    问题

    class Tree{
      public:
    
        struct nodeSon{
          struct node* node_ptr;    // (1)
          nodeSon* nextNodeSon_ptr;
        };
    };
    

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

    问题在于编译器不能假定此类型位于 class Tree 中——因为你没有说是这种情况——而是假定 struct node 指的是 global 命名空间。

    当你稍后在class Tree 中声明一个名为node 的类型时,已经太晚了; 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`
    }
    

    解决方案

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

    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
    };
    

    【讨论】:

    • 您,先生,在过去一年(或两年?)中,您在解释方面做得更好了
    • @sehe 我大约一年半前开始教书,也许这就是根本原因! :D
    • 这很有意义。
    • 惊人的解释! :D 非常清晰和准时。非常感谢,这绝对解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多