繁体   English   中英

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

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

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

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

但是,这似乎不起作用。 看起来在初始化m_collection之前正在调用构造函数TQueueViewerForm()。 由于TQueueViewerForm()尝试使用未初始化的对象,这使程序崩溃。

所以...我在这里有什么选择? 理想情况下,我只想在以某种方式初始化父类之前初始化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"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM