为什么下面的C++代码给出了下面提到的错误?为什么这不是用C++编写递归数据结构的惯用方式?这种编写C++的方式是否存在根本性错误?由编译器给出下面的C++程序有什么问题?
#include<iostream>
using namespace std;
class tree{
public:
virtual void inorder() {};
};
class emp_tree: public tree{
public:
void inorder(){
}
};
class non_emp_tree: public tree{
public:
tree left, right;
int val;
non_emp_tree(int v, tree l, tree r): val(v), left(l), right(r) {};
void inorder(){
left.inorder();
cout<<" "<<val<<" ";
right.inorder();
}
};
int main() {
tree leaf1 = non_emp_tree(1, emp_tree(), emp_tree());
tree leaf2 = non_emp_tree(3, emp_tree(), emp_tree());
tree root = non_emp_tree(2, leaf1, leaf2);
root.inorder();
return 0;
}
错误:(我无法理解的是大多数)
/tmp/ccAjhirw.o: In function `main':
b_t.cpp:(.text+0x16e): undefined reference to `tree::inorder()'
/tmp/ccAjhirw.o: In function `tree::tree()':
b_t.cpp:(.text._ZN4treeC2Ev[_ZN4treeC5Ev]+0x9): undefined reference to `vtable for tree'
/tmp/ccAjhirw.o: In function `tree::tree(tree const&)':
b_t.cpp:(.text._ZN4treeC2ERKS_[_ZN4treeC5ERKS_]+0xd): undefined reference to `vtable for tree'
/tmp/ccAjhirw.o: In function `non_emp_tree::inorder()':
b_t.cpp:(.text._ZN12non_emp_tree7inorderEv[_ZN12non_emp_tree7inorderEv]+0x19): undefined reference to `tree::inorder()'
b_t.cpp:(.text._ZN12non_emp_tree7inorderEv[_ZN12non_emp_tree7inorderEv]+0x56): undefined reference to `tree::inorder()'
/tmp/ccAjhirw.o: In function `tree::tree(tree&&)':
b_t.cpp:(.text._ZN4treeC2EOS_[_ZN4treeC5EOS_]+0xd): undefined reference to `vtable for tree'
/tmp/ccAjhirw.o:(.rodata._ZTI12non_emp_tree[_ZTI12non_emp_tree]+0x10): undefined reference to `typeinfo for tree'
/tmp/ccAjhirw.o:(.rodata._ZTI8emp_tree[_ZTI8emp_tree]+0x10): undefined reference to `typeinfo for tree'
collect2: error: ld returned 1 exit status
编辑:我改变到virtual void inorder() {}
即空的实现。但我仍然没有得到期望的输出,看起来root,leaf1和leaf2都调用树的顺序而不是它们各自的inorders。
可能重复[什么是未定义的引用/无法解析的外部符号错误,以及如何解决它?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved- external-symbol-error-and-how-do-i-fix) – Rakete1111
@ Rakete1111我不相信它是。或者,更确切地说,我认为OP的问题与该问题中描述的问题是垂直的。 – Xirema
@Xirema如果在常见问题中描述了问题,那为什么它不是重复的? – Rakete1111