Home > database >  How to initialize the array-like member variable in the constructor?
How to initialize the array-like member variable in the constructor?

Time:09-16

How to initialize the array-like member variable?

The visual studio code says:

no matching function for call to 'Node::Node()' gcc line 12 col 9

const int N = 100;

struct Node {
    int val, ch[2];
    /**
    void init(int _val) {
        this->val = _val, this->ch[0] = this->ch[1] = 0;
    }*/
    Node (int _val): val(_val) {
        this->ch[0] = this->ch[1] = 0;
    }
} tree[N];    // <--------- this is line 12


int main() {
    int a;
    cin >> a;
    tree[0] = Node(a);
}

CodePudding user response:

The problem is that when you wrote tree[N] you're creating an array whose elements will be default constructed but since there is no default constructor for your class Node, we get the mentioned error.

Also, Node doesn't have a default constructor because you've provided a converting constructor Node::Node(int) so that the compiler will not automatically synthesize the default ctor Note::Node().


To solve this you can add a default ctor Node::Node() for your class.

  • Related