在其他类构造函数中使用参数化构造函数 [英] use parameterized constructor in other classes constructor
问题描述
我担心这是一个非常基本的问题,但是我还是无法解决。
I fear that this is a very basic question, however, I was not able to solve it yet.
我有一个 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;
}
...
第二 B类
在构造函数中使用 A类
的实例:
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);
}
...
注意,默认构造函数的类A
从不使用。事实上,在我现实的用例中,使用任何类型的默认构造函数甚至没有意义,因为 _foo
必须动态分配。
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:
到'ClassA :: ClassA()'
no matching function for call to 'ClassA::ClassA()'
是否有一种使用 / code>作为
类B
中的对象,而不定义类A
的默认构造函数?
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?
推荐答案
ClassA
的默认构造函数是用过的。 ClassB
的 _objectA
使用它初始化,然后 您分配 ClassA(bar)
。
The default constructor of ClassA
is used. ClassB
's _objectA
is initialized with it and then you assign ClassA(bar)
to it.
您可以使用 constructor initializer lists :
ClassB::ClassB() : _objectA(bar)
{}
这篇关于在其他类构造函数中使用参数化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!