struct B {
int b;
B(int i = 0) : b(i) {}; // constructor
};
struct D : B {
int d;
};
int main () {
D obj = {1}; // <-- error
// D obj {1}; // <-- error (different)
}
Above code doesn't compiles, and gives:
error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘D’
The same is true, even if I remove the "constructor" line. If I remove =
sign, ie D obj {1};
then it gives below:
error: no matching function for call to ‘D::D(<brace-enclosed initializer list>)’
What is the correct syntax to fix such issue?
D
doesn't have a constructor taking an int
. If you want it to inherit B
's constructor, say so, like this:
struct D : B {
using B::B;
int d;
};
You probably want to do more than that though, given that D
has another int
member.
A more complete D
which initialises both B::b
(by calling B::B
) and D::d
would probably look like this:
struct D : B {
D(int d_) : B(d_), d(d_) {}
int d;
};
Either way, your code needs to say D
has a constructor taking an int
.
Link to working example using your code and my snippet: http://goo.gl/YbSSHn
In what you've written D
has only a default constructor and does not know how to invoke B::B(int i)
. All you have to do is to provide a corresponding constructor in D
like:
struct D : B {
D(int i) : B(i) {}//;
int d;
};
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.