【发布时间】:2021-04-04 11:04:36
【问题描述】:
下面的代码由二叉树数据结构组成:
#include <bits/stdc++.h>
#define DEFAULT_NODE_VALUE 0
using namespace std;
template <class T>
class node{
public:
T val;
node* right = 0;
node* left = 0;
node(T a):val(a){}
};
template <class T>
class tree{
public:
node<T>* root = new node<T>(DEFAULT_NODE_VALUE);
tree(T inp_val){
root->val = inp_val;
}
void inorder_traverse(node<T>* temp){
if (!temp)
return;
inorder_traverse(temp->left);
cout << temp->val << " -> ";
inorder_traverse(temp->right);
}
void inorder_traverse(){
inorder_traverse(root);
}
};
int main()
{
tree<string> my_tree("mantap");
my_tree.root->right = new node<string>("ok");
my_tree.root->left = new node<string>("haha");
my_tree.inorder_traverse();
return 0;
}
当我运行它时,它向我显示了如下所示的异常:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
谁能帮我解决这个运行时错误,好吗?提前谢谢...
【问题讨论】:
-
首先,永远不要垃圾邮件无关的语言标签(如您拥有的 C 语言标签)。其次,don't include
<bits/stdc++.h>。三是找some good C++ books好好学习,最好上几节课。这应该告诉你为什么你的DEFAULT_NODE_VALUE不能适用于所有事情(或者为什么它不是真正需要的)。 -
当构造函数
tree::tree(T inp_val)为root提供值时,为什么还要DEFAULT_NODE_VALUE? -
您指定了错误的默认值
std::string,而是使用此语法node<T>* root = new node<T>(T{});
标签: c++ exception runtime-error runtime