如何从C ++中的子C中使用初始化超类参数? [英] How can i initialize superclass params from within the child c-tor in C++?
问题描述
观察以下示例:
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的参数
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.
是这样做的正确方法?
感谢,
Amir
Thanks, Amir
我的具体情况下,参数不是原始的,这个例子只是帮助我解释自己。
PS: In my particular case, the parameters are not primitives, this example just helped me to explain myself.
推荐答案
参数不是基元。那么你有这样的东西吗?
"The parameters are not primitives". So you have something like this?
class Param { /*...*/ };
class A {
public:
A(const Param& param1, const Param& param2, const Param& param3);
};
class B : public A {
public:
B();
private:
Param m_param1;
Param m_param2;
Param m_param3;
};
并且您要传递 B
到 A
的构造函数。这个怎么样?
And you want to pass the members of B
to the constructor of A
. How about this?
class B_params {
protected:
B_params(int v1, int v2, int v3);
Param m_param1;
Param m_param2;
Param m_param3;
};
class B : private B_params, public A {
public:
B();
};
B_params::B_params(int v1, int v2, int v3)
: m_param1(v1), m_param2(v2), m_param3(v3) {}
B::B() : B_params(1,2,3), A(m_param1, m_param2, m_param3) {}
只需确保 B $ c>列表中的
B_params
在 A
$ c>是继承的类。
Just make sure B_params
comes before A
in the list of B
's inherited classes.
这篇关于如何从C ++中的子C中使用初始化超类参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!