我如何从 C++ 的子 c-tor 中初始化超类参数?
看下面的例子:
class A {
public:
A(int param1, int param2, int param3) {
// ...
}
};
class B : public A {
public:
B() : m_param1(1), m_param(2), m_param(3), A(m_param1, m_param2, m_param3) {
// ...
}
};
B b;
显然,当创建“b”时,A的ctor将在B的参数初始化之前被调用。
这条规则阻止我创建简化类初始化的“包装”类。
这样做的“正确方法”是什么?
谢谢, Amir
PS:在我的特定情况下,参数不是基元,这个例子只是帮助我解释自己。
Watch the following example:
class A {
public:
A(int param1, int param2, int param3) {
// ...
}
};
class B : public A {
public:
B() : m_param1(1), m_param(2), m_param(3), A(m_param1, m_param2, m_param3) {
// ...
}
};
B b;
Obviously, when "b" will be created, A's ctor will be called before the parameters of B will be initialized.
This rule prevents me from creating "wrapper" classes which simplify the class's initialization.
What is the "right way" for doing it?
Thanks,
Amir
PS: In my particular case, the parameters are not primitives, this example just helped me to explain myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需调用 A 的构造函数即可:
编辑:
只需阅读您对原始帖子的评论即可。弄清楚这些事情很重要:)无论如何,如果您想在 B 中创建新数据,在 B 中跟踪它,然后将其传递给 A,这个答案仍然成立:
Just call A's constructor:
EDIT:
Just read your comment to your original post. It's important to be clear about these things :) Anyway, this answer still holds true if you want to create new data in B, track it in B, and pass it to A:
“参数不是基元”。那么你有这样的东西吗?
并且您希望将
B
的成员传递给A
的构造函数。这个怎么样?只需确保在
B
的继承类列表中B_params
位于A
之前。"The parameters are not primitives". So you have something like this?
And you want to pass the members of
B
to the constructor ofA
. How about this?Just make sure
B_params
comes beforeA
in the list ofB
's inherited classes.不确定我是否明白你的问题。
如果您只想帮助您使用某些给定参数初始化 A,则应该使用具有默认值的 A 构造函数:
Not sure I'm getting your question.
If you just want something that helps you to initialize A with some given parameters, you should use an A constructor with default values: