2014-02-13 126 views
0

我想创建一个类,将成员对象传递给它的父对象进行初始化。下面的代码显示了我想要做的事情。如何将类的成员对象传递给其基类的构造函数?

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被初始化之前被调用。由于TQueueViewerForm()尝试使用未初始化的对象,因此这会使程序崩溃。

那么......我在这里做了什么选择?理想情况下,我想在父类初始化之前初始化m_collection。

回答

0

在孩子的构造函数之前调用派生类的父构造函数总是。你有一个选择是把你想要执行的初始化代码放在父类的一个单独的函数中,并在派生类的构造函数中调用该函数。

1

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

在这种情况下,在初始化之前,你将基本类的随机内存传递给你的基类。

0
class CollectionHolder { 
public: 
    DOMMsgCollectionEditorImpl m_collection; 
}; 

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

有点太微妙,我的口味。就我个人而言,我试图找到一个不需要我去执行这样的体操的设计。

+0

哦,哇。这将解决这个问题,但我不认为我可以原谅自己写这种代码... – QuestionC

+0

同意。这看起来过于复杂,并且可能不值得为不熟悉代码库的新维护人员进行维护。最好重新考虑问题并尝试不同的方法。 – jia103

0

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

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" 
} 
相关问题