C++ struct constructor

2019-04-06 13:30发布

问题:

I tried to create my own structure. So I wrote this piece of code.

struct node
{
    int val, id;
    node(int init_val, int init_id)
    {
        val = init_val;
        id = init_id;
    }
};

node t[100];

int main()
{
...
}

I tried to compile my program. But I got an error:

error: no matching function for call to 'node::node()'
note: candidates are:
note: node::node(int, int)
note: candidate expects 2 arguments, 0 provided
note: node::node(const node&)
note: candidate expects 1 argument, 0 provided

回答1:

node t[100];

will try to initialise the array by calling a default constructor for node. You could either provide a default constructor

node()
{
    val = 0;
    id = 0;
}

or, rather verbosely, initialise all 100 elements explicitly

node t[100] = {{0,0}, {2,5}, ...}; // repeat for 100 elements

or, since you're using C++, use std::vector instead, appending to it (using push_back) at runtime

std::vector<node> t;


回答2:

This will fix your error.

struct node
{
int val, id;
node(){};

node(int init_val, int init_id)
{
    val = init_val;
    id = init_id;
}
};

You should declare default constructor.