[英]How to pass a class's member object to its base class's constructor?
I want to make a class that passes a member object to its parent for initialization. 我想制作一个将成员对象传递给其父对象进行初始化的类。 The below code shows what I'm trying to do.
下面的代码显示了我正在尝试做的事情。
class TQueueViewerForm1 : public TQueueViewerForm
{
private: // User declarations
DOMMsgCollectionEditorImpl m_collection;
public: // User declarations
__fastcall TQueueViewerForm1(TComponent* Owner);
};
__fastcall TQueueViewerForm1::TQueueViewerForm1(TComponent* Owner)
: TQueueViewerForm(Owner, m_collection)
{
}
This doesn't seem to work however. 但是,这似乎不起作用。 It looks like the constructor TQueueViewerForm() is being called before m_collection is initialized.
看起来在初始化m_collection之前正在调用构造函数TQueueViewerForm()。 This crashes the program since TQueueViewerForm() tries to use the uninitialized object.
由于TQueueViewerForm()尝试使用未初始化的对象,这使程序崩溃。
So... what are my choices here? 所以...我在这里有什么选择? Ideally I would like to just initialize m_collection before the parent class is initialized somehow.
理想情况下,我只想在以某种方式初始化父类之前初始化m_collection。
You have to remember the order of operations with inheritance. 您必须记住继承的操作顺序。 When you construct an instance of a class, first the base component gets constructed (ie your base class constructor gets run to completion);
当构造一个类的实例时,首先构造基组件(即,基类构造函数运行完成); then, your class' members are initialized, and finally, your class' constructor gets run.
然后,初始化您的类的成员,最后运行您的类的构造函数。
In this case, you're passing somewhat-random memory to your base class before it ever got initialized. 在这种情况下,您要在初始化之前将某种程度的内存传递给基类。
A derived class's parent constructor will always be called before the child's constructor. 派生类的父构造函数将始终在子构造函数之前被调用。 One option you have is to put the initialization code that you're trying to execute in a separate function in the parent class and call that function in the derived class's constructor.
您有一个选择,就是将要执行的初始化代码放在父类的单独函数中,并在派生类的构造函数中调用该函数。
class CollectionHolder {
public:
DOMMsgCollectionEditorImpl m_collection;
};
class TQueueViewerForm1 :
private CollectionHolder, // important: must come first
public TQueueViewerForm {
};
A bit too subtle for my taste. 我的口味有点微妙。 Personally, I'd try to find a design that doesn't require me to perform such gymnastics.
就个人而言,我会尝试找到一种不需要我进行此类体操的设计。
You can pass parameters to a base classes constructor using the initialization list of the derived classes constructor. 您可以使用派生类构造函数的初始化列表将参数传递给基类构造函数。
class Parent
{
public:
Parent(std::string name)
{
_name = name;
}
std::string getName() const
{
return _name;
}
private:
std::string _name;
};
//
// Derived inherits from Parent
//
class Derived : public Parent
{
public:
//
// Pass name to the Parent constructor
//
Derived(std::string name) :
Parent(name)
{
}
};
void main()
{
Derived object("Derived");
std::cout << object.getName() << std::endl; // Prints "Derived"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.