簡體   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