简体   繁体   English

C ++使用派生类构造函数填充受基类保护的成员

[英]C++populating base class protected member using derived class constructor

I have something like this: 我有这样的事情:

Class Base
{
  public:
    Base();
  protected:
    someType myObject;
}

Class Child:public someNamespace::Base
{
   //constructor
   Child(someType x):myObject(x){}
}

Class Child, and Base are in 2 different namespaces... Compiler complains that my Child class does not have a field called myObject 子类和基类位于2个不同的命名空间中...编译器抱怨我的子类没有名为myObject的字段

Anyone know why? 有人知道为什么吗? Is it because its illegal to populate a Base member from a Child constructor? 是因为从Child构造函数中填充Base成员是非法的吗?

Thanks 谢谢

You cannot initialize the inherited member like that. 您不能像这样初始化继承的成员。 Instead, you can give the base class a constructor to initialize that member, then the derived class can call that constructor. 相反,可以给基类一个构造函数来初始化该成员,然后派生类可以调用该构造函数。

class Base
{
  public:
    Base(someType x) : myObject{x} {}
  protected:
    someType myObject;
}

class Child : public Base
{
  public:
    //constructor
    Child(someType x) : Base(x) {}
}

In general, a class should be responsible for initializing its own members. 通常,一个类应该负责初始化其自己的成员。

The problem here is that you are initializing your inherited myObject in the initialization list. 这里的问题是您正在初始化列表中初始化继承的myObject When an object of the derived class is created, before entering the body of the constructor of the derived class the constructor of the base class is called (by default, if base class has default or no parameter constructor, otherwise you have to explicitly call the constructor in the initialization list) . 创建派生类的对象时,在进入派生类的构造函数的主体之前,将调用基类的构造函数(默认情况下,如果基类具有默认或没有参数构造函数,否则必须显式调用初始化列表中的构造函数)

So, when you do :: Class Child:public someNamespace::Base your constructor for the base class has not yet been called, which is why your compiler complains :: Child class does not have a field called myObject , that is you are actually trying to assign a value to something which has not yet been declared and defined! 因此,当执行:: Class Child:public someNamespace::Base ,尚未调用基类的构造函数,这就是编译器抱怨的原因:: 子类没有名为myObject的字段 ,也就是说,您实际上是试图给尚未声明和定义的值赋值! It will get defined after the constructor the Base class enters its execution. Base类的构造函数进入其执行之后,将对其进行定义。

So, your Child class constructor will look something like this :: 因此,您的Child类构造函数将如下所示:

   Child(someType x) {
      myObject = x;
   }

Working ideone link :: http://ideone.com/70kcdC 工作ideone链接:: http://ideone.com/70kcdC

I found this point missing in the answer above, so I thought it might actually help! 我发现以上答案中缺少这一点,因此我认为这可能实际上有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM