类中带有非默认构造函数的类(c++)
Class with non-default constructor, within a class (C++)
我有一个类,在它的构造函数中有两个参数,一个int和一个void(*)(void)所以通常当我需要调用它时,我像这样做:
obj_child (int_value, pointer_to_foo);
现在我想要的是实例化obj_child 与常量参数,在另一个类。
所以我试了:
class obj_parent
{
private:
obj_child child_instantiation (int_value, pointer_to_foo);
};
,但这似乎给了我两个编译器错误的行我声明child_instantiation所以我猜参数不能传递到那里,但在其他地方。
注意child_instantiations应该对所有obj_parent实例化具有相同的参数,因此它们不应该作为obj_parent构造函数参数传递。
声明类指针,然后在堆编译上创建一个新的,但我不想这样做,我不知道它是否有效(我的调试器不能观察引用,所以很难监控它的值)。
class obj_parent
{
private:
obj_child *child_instantiation;
};
obj_parent::
obj_parent (void)
{
child_instantiation = new obj_child child_instantiation (int_value, pointer_to_foo);
}
谢谢!
(请不要介意语义,child - parent与继承无关,只是现在想不出更好的名字)
必须在类的构造函数中初始化对象。
obj_parent() : child_instantiation (int_value, pointer_to_foo) {}
你可以这样做
// note that this class has no constructor with 0 args
class PrimaryClass {
public:
PrimaryClass(int arg1, void* arg2) {
// do something here
}
};
class SecondaryClass {
private:
PrimaryClass my_obj;
public:
// We call the constructor to my_obj here (using initialization lists)
SecondaryClass(int arg1, void* arg2) : my_obj(arg1, arg2) {
// other stuff here, maybe
}
};
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为