简体   繁体   中英

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. 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:

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?

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. 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 .

You can call it like this:

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

or else reinstate the default constructor for person , with:

person() = default;

Cigien's answer is correct and the reason why you get that error. 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 . 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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