问题
I fear that this is a very basic question, however, I was not able to solve it yet.
I have a class A
// classA.h
...
class ClassA {
public:
ClassA();
ClassA(int foo);
private:
int _foo;
...
}
// classA.cpp
ClassA::ClassA() {
_foo = 0;
}
ClassA::ClassA(int foo) {
_foo = foo;
}
...
A second class B
uses an instance of class A
in the constructor:
// classB.h
...
#include "classA.h"
#define bar 5
class ClassB {
public:
ClassB();
private:
ClassA _objectA;
...
}
// classB.cpp
ClassB::ClassB() {
_objectA = ClassA(bar);
}
...
Note that the default constructor of class A
is never used. In fact in my real world use case it would not even make sense to use any kind of a default constructor as _foo
has to be dynamically assigned.
However, if I remove the default constructor, the compiler returns an error:
no matching function for call to 'ClassA::ClassA()'
Is there a way to use an instance of class A
as an object in class B
without defining a default constructor for class A
? How would this be done?
回答1:
The default constructor of ClassA
is used. ClassB
's _objectA
is initialized with it and then you assign ClassA(bar)
to it.
You can solve your problem by using constructor initializer lists:
ClassB::ClassB() : _objectA(bar)
{}
回答2:
Just write
ClassB::ClassB() : _objectA(bar)
{
}
The problem is that when the body of the constructor of the ClassB
is executed the data member _objectA
is already constructed and inside the body there is used the copy assignment operator
ClassB::ClassB() {
_objectA = ClassA(bar);
^^^^^^^^^^^^^^^^^^^^^^^^
}
Thus you can remove the default constructor of the ClassA
.
来源:https://stackoverflow.com/questions/40665414/use-parameterized-constructor-in-other-classes-constructor