类内具有非默认构造函数的类 (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_instantiation 对于所有 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);
}
谢谢!
(请不要介意语义,子-父与继承无关,只是现在想不出更好的名字)
I have a class which takes two arguments on it's constructor, an int and a void(*)(void) so normally when I need to call it I do it like this:
obj_child (int_value, pointer_to_foo);
Now what I want is to instantiate the obj_child with constant arguments, within another class.
So I tried:
class obj_parent
{
private:
obj_child child_instantiation (int_value, pointer_to_foo);
};
but this seems to give me two compiler errors on the line I declare child_instantiation so I guess the arguments can't be passed there but somewhere else.
Mind you child_instantiations are supposed to have the same arguments for all obj_parent instantiations, so they shouldn't be passed as obj_parent constructor arguments.
Declaring the class pointer and then creating a new one on the heap compiles, but I don't want to do it that way and I don't know if it works (my debugger can't watch the reference so it's very hard to monitor it's values).
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);
}
Thanks!
(Please don't mind the semantics, child - parent has nothing to do with inheritance, just couldn't think better names right now)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须在类的构造函数中初始化该对象。
You have to initialize the object in the constructor of the class.
这是你应该如何做的
Here's how you'd do it