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