如何将类的成员对象传递给其基类的构造函数?
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)
{
}
然而,这似乎不起作用。 看起来构造函数 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"
}
相关文章:
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 在成员构造函数之后调用基类构造函数
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 如何在 C++ 中将参数传递给基类构造函数
- 将数据成员的指针传递给基类构造函数是否安全?
- 使用基类构造函数初始化儿童类
- 使用基类构造函数的子类构造函数的大纲定义
- MSVC 无法识别继承模板类的模板类的"直接"基类构造函数
- 子类的构造函数后跟冒号后的基类构造函数是什么意思?
- 是否可以使用基类构造函数通过派生类将值初始化为基类私有成员?
- 当派生类无法轻易将参数传递到基类时,如何调用基类构造函数
- 是否可以在运行时切换到不同的基类构造函数?
- 对基类构造函数的未定义引用
- 如何为基类构造函数中的每个子类执行特定任务
- 将类传递到基类构造函数的模板参数中?
- 如何在基类构造函数中使用派生类成员
- (为什么)纯虚拟派生类中是否需要虚拟基类构造函数调用?
- 使用相同的参数调用基类C++构造函数