如何将类的成员对象传递给其基类的构造函数?

How to pass a class's member object to its base class's constructor?

本文关键字:基类 构造函数 成员对象      更新时间:2023-10-16

我想创建一个将成员对象传递给其父对象进行初始化的类。 下面的代码显示了我正在尝试执行的操作。

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)
{
}

然而,这似乎不起作用。 看起来构造函数 TQueueViewerForm() 在初始化之前m_collection被调用。 这会使程序崩溃,因为 TQueViewerForm() 尝试使用未初始化的对象。

那么......我在这里有什么选择? 理想情况下,我想在以某种方式初始化父类之前初始化m_collection。

您必须记住继承的操作顺序。当你构造一个类的实例时,首先构造基组件(即你的基类构造函数运行完成);然后,初始化类的成员,最后运行类的构造函数。

在这种情况下,您将在基类初始化之前将一些随机内存传递给基类。

生类的父构造函数将始终在子构造函数之前调用。您有一个选择是将尝试执行的初始化代码放在父类中的单独函数中,并在派生类的构造函数中调用该函数。

class CollectionHolder {
public:
  DOMMsgCollectionEditorImpl m_collection;
};
class TQueueViewerForm1 :
  private CollectionHolder,  // important: must come first
  public TQueueViewerForm {
};

有点太微妙了,不符合我的口味。就我个人而言,我会尝试找到一种不需要我进行此类体操的设计。

可以使用派生类构造函数的初始化列表将参数传递给基类构造函数。

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"
}