我正在实现一个简单的Tree类来在解析器中使用,我需要遍历解析树的结构并逐步构建它。为什么我的deque元素四处移动?
这是类的精简版,演示了这个问题(在this repl.it session可执行文件):
template <typename T>
class Tree {
T val;
std::deque<Tree<T>> children;
public:
Tree() {}
Tree(T value) : val(value) {}
Tree(T value, std::deque<Tree<T>> children) : val(value), children(children) {}
std::deque<Tree<T>> getChildren() { return this->children; }
void appendChild(T value) {
this->children.push_back(value);
// this->children.emplace_back(value);
std::cout << "Appended child to node with value " << this->val << ".\n";
printChildren();
}
void printChildren() {
std::cout << "children for " << this << "(" << this->val << ")"
<< ": { ";
for (auto &child : this->children) {
std::cout << &child << "(" << child.val << ") ";
}
std::cout << "}\n";
}
};
对于每个节点,孩子们都存储在一个std::deque
所以孩子们可以加入到任何一端。在测试我的课程时,我发现我不能依赖增量树建立的结构,而是使用初始化程序列表一次性完成。
下面是一些代码行使类,并显示发生的事情:
std::cout << "Constructing Tree\n\n";
Tree<int> t(1);
t.appendChild(2);
t.getChildren()[0].appendChild(3);
std::cout << "\n\nPrinting tree from main\n\n";
t.printChildren();
t.getChildren()[0].printChildren();
这有以下的输出:
Constructing Tree
Appended child to node with value 1.
children for 0x7ffe9fd41820(1): { 0xb69080(2) }
Appended child to node with value 2.
children for 0xb694a0(2): { 0xb696b0(3) }
Printing tree from main
children for 0x7ffe9fd41820(1): { 0xb69080(2) }
children for 0xb698c0(2): { }
正如你所看到的,节点与价值2
地址每次打印出来都不一样。当它首先附加到1
节点时,它的地址为0xb69080
。它得到自己的孩子后,它的地址为0xb694a0
。然后,当从main
函数访问它时,它的地址为0xb698c0
。
此外,它似乎当它被移动它不知何故失去了它的孩子。最后一行应显示2
节点有一个值为3
的单个子节点。
这是怎么回事?
谢谢!我正在思考我需要实现移动/复制构造函数的思路,但通过引用返回是我想要做的。 – Kevin