问题描述
我有一个关于在派生类的构造函数中初始化继承成员的问题.示例代码:
I've a question about initialization of inherited members in constructor of derived class. Example code:
class A
{
public:
int m_int;
};
class B: public A
{
public:
B():m_int(0){}
};
这段代码给了我以下输出:
This code gives me the following output:
在构造函数'B::B()'中:第 10 行:错误:B"类没有任何名为m_int"的字段
(参见 http://codepad.org/tn1weFFP)
我猜为什么会这样?m_int
应该是B
的成员,并且m_int
在中初始化时父类
发生(因为父构造函数在继承类的成员初始化之前运行).我的推理哪里出错了?这段代码到底发生了什么?A
应该已经被初始化>B
I'm guessing why this happens? m_int
should be member of B
, and parent class A
should already be initialized when initialization of m_int
in B
happens (because parent constructors run before member initialization of inherited class). Where is a mistake in my reasoning? What is really happens in this code?
EDIT
:我知道初始化此成员的其他可能性(基构造函数或派生构造函数中的赋值),但我想了解为什么我尝试它的方式是非法的?一些特定的 C++ 语言功能之类的?如果可能,请指出 C++ 标准中的一段.
EDIT
: I'm aware of other possibilities to initialize this member (base constructor or assignment in derived constructor), but I want to understand why is it illegal in the way I try it? Some specific C++ language feature or such? Please point me to a paragraph in C++ standard if possible.
推荐答案
你需要为 A 创建一个构造函数(它可以被保护,所以只有 B 可以调用它),它像你一样初始化 m_int,然后你调用 :A(0)
你有 :m_int(0)
You need to make a constructor for A (it can be protected so only B can call it) which initializes m_int just as you have, then you invoke :A(0)
where you have :m_int(0)
您也可以在 B 的构造函数的主体中设置 m_int = 0
.它是可访问的(正如您所描述的)它只是在特殊的构造函数语法中不可用.
You could also just set m_int = 0
in the body of B's constructor. It is accessible (as you describe) it's just not available in the special constructor syntax.
这篇关于C++:继承字段的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!