C ++:继承字段的初始化 [英] C++: Initialization of inherited field

查看:145
本文介绍了C ++:继承字段的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在派生类的构造函数中初始化继承成员的问题。示例代码:

  class A 
{
public:
int m_int;
};

class B:public A
{
public:
B():m_int(0){}
};

此代码为我提供以下输出:



在构造函数'B :: B()':
行10:错误:类'B'没有任何名为'm_int'的字段
p>

(请参阅 http://codepad.org/tn1weFFP



我猜猜为什么会发生这种情况? m_int 应为 B 的成员,父类 A 应该已经在 m_int B 中初始化时被初始化(因为父构造函数在继承类的成员初始化之前运行)。我的推理中的错误在哪里?这个代码真的发生了什么?



EDIT :我知道初始化这个成员的其他可能性基础构造函数或派生在派生构造函数),但我想明白为什么它是非法的,我的尝试方式?一些特定的C ++语言特性等等?如果可能,请指定一个C ++标准的段落。

解决方案

您需要为A构建一个构造函数所以只有B可以调用它)它初始化m_int就像你有,然后你调用:A(0)其中你有:m_int(0) c>



您也可以在B的构造函数正文中设置 m_int = 0 。它是可访问的(如你所述),它只是在特殊构造函数语法中不可用。


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:

In constructor 'B::B()': Line 10: error: class 'B' does not have any field named 'm_int'

(see http://codepad.org/tn1weFFP)

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: 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.

解决方案

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)

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 ++:继承字段的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆