1

我试图实现一个简单的节点类,但是当我尝试通过根节点访问子节点时,它是空的,但是如果我直接访问子节点,它就会正确填充。我是否在某个地方出现了逻辑错误,或者有人可以提示我出了什么问题?

Node::Node(QString name, Node *parent)
{
    this->name = name;
    this->parent = parent;

    parent->children.append(this);
}

\\

 class Node
    {
    public:
        Node(QString name) { this->name = name; }
        Node(QString name, Node *parent);
        ~Node(void);

    void addChild(Node *child);

    QString getName() { return name; }
    Node* getChild(int row) { return children[row]; }
    Node* getParent() { return parent; }

    int childCount() { return children.size(); }
    int getRow() {return this->parent->children.indexOf(this);}

    QString log(int tabLevel = -1);

private:
    QString name;
    QList<Node*> children;
    Node *parent;
};

我试图找出错误,结果是,子节点似乎有两个不同的地址,所以有两个不同的对象,但我不知道为什么:/

    Node rootNode = Node("rootNode");
Node childNode0 = Node("childNode0", &rootNode);
Node childNode1 = Node("childNode1", &rootNode);
Node childNode2 = Node("childNode2", &rootNode);
Node childNode3 = Node("childNode3", &childNode0);
Node childNode4 = Node("childNode4", &childNode0);

qDebug() << "RootNode: " + rootNode.getName() << " | RootChilds: " << rootNode.childCount();
qDebug() << "NodeName: " +rootNode.getChild(0)->getName() << " | NodeChilds: " << rootNode.getChild(0)->childCount();

for(int i = 0; i < childNode0.childCount(); i++)
{
    qDebug() << "NodeName: " << childNode0.getName() << " | NodeChilds: " << childNode0.childCount() << "Child Nr: " << i << " Name -> " << childNode0.getChild(i)->getName();
} 

qDebug() << "Adress via root: " << rootNode.getChild(0) << "\nAdress via node: " << &childNode0 ;

}

输出:

"RootNode: rootNode"  | RootChilds:  3 
"NodeName: childNode0"  | NodeChilds:  0 
NodeName:  "childNode0"  | NodeChilds:  2 Child Nr:  0  Name ->  "childNode3" 
NodeName:  "childNode0"  | NodeChilds:  2 Child Nr:  1  Name ->  "childNode4" 
Adress via root:  0x41fc84 
Adress via node:  0x41fcc0 

我希望有一个人可以帮助我

问候

4

2 回答 2

2

当您这样做时,您正在向父母Node提供临时地址Node

Node childNode0 = Node("childNode0", &rootNode);
//                ^ rootNode gets this temporary Node as its first child

而不是Node通过从临时复制来构造 s,而是:

Node childNode0("childNode0", &rootNode);
于 2013-01-01T05:02:55.477 回答
0

我不认为return children[row];在功能getChild上是正确的。你确定不想要*children.begin()

不同之处在于,children[row]假设您有一个数组QList<Node*>'s并且您想要访问第行 QList,而*children.begin()实际上引用了 QList 的第一个元素。

于 2013-01-01T04:39:17.487 回答