我试图实现一个简单的节点类,但是当我尝试通过根节点访问子节点时它是空的,但如果我直接访问子节点,它就会被正确填充。我有某个逻辑错误,或者有人给我一个提示错误吗?
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
我希望有人可以帮助我
此致
答案 0 :(得分:2)
当您执行
时,您将父母Node
的地址提供给临时Node
Node childNode0 = Node("childNode0", &rootNode);
// ^ rootNode gets this temporary Node as its first child
不是通过复制来构建Node
,而是执行:
Node childNode0("childNode0", &rootNode);
答案 1 :(得分:0)
我认为函数return children[row];
中的getChild
不正确。您确定不想要*children.begin()
吗?
不同之处在于,children[row]
假设您有一个QList<Node*>'s
数组,并且您想要访问第Q行,而*children.begin()
实际上引用了QList的第一个元素