Because of the most vexing parse, if you have a private member definition in a class header which is a class type like this:
box newBox;
and box has a constructor that accepts no arguments, does that mean you have to either make it a pointer or a reference type?
how do you get around this problem? It seems inelegant to be able to declare some classes this way but not the one's that accept no arguments. or am I misunderstanding something?
be开发者_如何学JAVAcause as far as I understand it, if it accepts no arguments, then this is not only a definition, but initialisation as well.
class whatever
{
private:
box newBox; //is this not allowed because of the most vexing parse? because it's a
//header file and because of the MVP this is initialisation as well? or
//am I getting confused about something?
};
class box
{
public:
box();
}
The following works just fine:
struct Foo {
}
struct Bar {
Foo foo;
}
No MVP, no ambiguity. Everything is fine. Inside a class-declaration Foo foo;
is a member-declaration. It cannot be initialized there, initialization is done (explicitly or implicitly) in the constructor (of Bar
in this case).
If the only constructor accepts no arguments, this is the canonical constructor that's called every time you construct an instance of the class which has newBox
as an element. It's still always a new box
object, though it'll always look the same.
You can test it this way:
class foo {
public:
foo() {
std::cout << "Constructed a foo.\n";
}
};
class bar{
foo afoo;
public:
bar() {}
};
int main() {
std::cout << "Request new bar: ";
bar bar1;
std::cout << "Request another new bar: ";
bar bar2;
return 0;
}
Output:
Request new bar: Constructed a foo.
Request another new bar: Constructed a foo.
There is nothing wrong about your whatever
class, besides that you need to move the definition of box
before that of whatever
, so that box
can be used there. When you create an instance of whatever
, the newBox
will be initialized with the default constructor of the box
class.
If you want to be explicit about the initialization or customize it in some way, you have to add a constructor to the whatever
class. For example:
class whatever {
private:
box newBox;
public:
whatever() : newBox() {
// ...
}
};
This is an example of the most vexing parse:
box newBox();
This is not:
box newBox;
精彩评论