C++ 在类(C+;+;)中使用非默认构造函数初始化
我有一个类,它的构造函数上有两个参数,一个int和一个void(*)(void),所以通常当我需要调用它时,我会这样做:C++ 在类(C+;+;)中使用非默认构造函数初始化,c++,class,constructor,C++,Class,Constructor,我有一个类,它的构造函数上有两个参数,一个int和一个void(*)(void),所以通常当我需要调用它时,我会这样做: obj_child (int_value, pointer_to_foo); 现在我想在另一个类中用常量参数实例化obj_子对象 所以我试着: class obj_parent { private: obj_child child_instantiation (int_value, pointer_to_foo); }; 但在我声明child
obj_child (int_value, pointer_to_foo);
现在我想在另一个类中用常量参数实例化obj_子对象
所以我试着:
class obj_parent
{
private:
obj_child child_instantiation (int_value, pointer_to_foo);
};
但在我声明child_实例化的那一行,这似乎给了我两个编译器错误,所以我猜参数不能传递到那里,只能传递到其他地方
请注意,对于所有obj_父实例化,子实例化应该具有相同的参数,因此它们不应该作为obj_父构造函数参数传递
声明类指针,然后在堆编译中创建一个新指针,但我不想这样做,也不知道它是否有效(我的调试器无法监视引用,因此很难监视它的值)
谢谢
(请不要介意语义,child-parent与继承无关,只是现在想不出更好的名称)您必须在类的构造函数中初始化对象
obj_parent() : child_instantiation (int_value, pointer_to_foo) {}
必须在类的构造函数中初始化对象
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
}
};
这是你要怎么做的
// 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
}
};