简体   繁体   English

如何将 class object 存储到二叉搜索树节点中?

[英]How to store a class object into a binary search tree node?

I am trying to create a node to a binary search tree that is able to store objects of a class.我正在尝试为能够存储 class 对象的二叉搜索树创建一个节点。 This is what i have so far:这是我到目前为止所拥有的:

struct person
{
string name;
int age;
person(string, int);
};

struct node 
{
person p;
node* left;
node* right;
};

When I try to declare a node in the main such as:当我尝试在 main 中声明一个节点时,例如:

int main(){

node* root1 = new node();
root1->p("bob", 25);

return 0;
}

I am received the following error messages: Call to implicitly-deleted default constructor of 'node' & Type 'person' does not provide a call operator我收到以下错误消息:调用隐式删除的“节点”和类型“人”的默认构造函数不提供调用运算符

Can someone point out what im doing wrong?有人可以指出我做错了什么吗? I thought that by constructing the object in the main with parameters would automatically call the constructor of the person class?我以为通过在main中使用参数构造object会自动调用人class的构造函数?

When you create root1 , p is constructed, and you can't call the constructor on an existing object, so the compiler thinks you are doing a function call.当您创建root1时,将构造p ,并且您不能在现有 object 上调用构造函数,因此编译器认为您正在执行 function 调用。 Instead, you can do:相反,您可以这样做:

root1->p = person{"bob", 25};

Also, this line:另外,这一行:

node* root1 = new node();

won't compile, since there is no default constructor for person .不会编译,因为person没有默认构造函数。

You can call it like this:你可以这样称呼它:

node* root1 = new node{{"bob", 25}};

or else reinstate the default constructor for person , with:或者恢复person的默认构造函数,使用:

person() = default;

Cigien's answer is correct and the reason why you get that error. Cigien 的答案是正确的,也是您收到该错误的原因。 This is just something you could do to make your binary search tree more general.这只是你可以做的让你的二叉搜索树更通用的事情。

If you really want to go fancy than you could look into template classes .如果你真的想要 go 比你可以看看模板类 These allow you to specify the general idea of te program independent of the type the eventual member will have.这些允许您指定程序的一般概念,而与最终成员将具有的类型无关。

That would look something like:这看起来像:

template<class t>
struct node 
{
  t data;
  node* left;
  node* right;
}

And pointer definition would look like:指针定义如下所示:

int main(){

  node<person>* root1 = new node<person>();

  return 0;
}

(this is also how the implement something like std::vector ) (这也是实现类似std::vector的方式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM