简体   繁体   English

C ++中的多级继承

[英]Multilevel Inheritance in C++

Let's say I have a base class A and class B derives from it. 假设我有一个基类A,而类B是从它派生的。 Class C from B and so on ..... Y from Z. B的C类,依此类推... Z的Y.

Who will be responsible for initializing the data members of class A, when I instantiate class Z? 当我实例化类Z时,谁将负责初始化类A的数据成员?

When you inherit from a class, the base class's constructor is called prior to the derived class's. 从类继承时,基类的构造函数在派生类的构造函数之前被调用。 You can control what gets passed to it using the initializer list: 您可以使用初始化列表控制传递给它的内容:

struct A
{
    A();
    A(int);
}

struct B
{
    B(){} // A() is called implicitly.
    B(int x) : A(x) {} // A(int) is called explicitly.
}

Any class derived along the chain can be responsible for initializing the data members depending on their accessibility. 沿链派生的任何类都可以负责初始化数据成员,具体取决于它们的可访问性。

One common method is to have class A`s constructor demand values for the data members. 一种常见的方法是为数据成员提供A类的构造函数需求值。 Class B would add these variables to it's constructor and so on. B类会将这些变量添加到其构造函数中,依此类推。

It could be any of the classes A through Z, it completely depends on your situation. 可以是A到Z的任何类,这完全取决于您的情况。 If class A takes param ab and c in its constructor then class B must provide these, if it in turn in its constructor expects abc to be passed then it would be down to class C to provide these and so on. 如果类A在其构造函数中使用参数ab和c,则类B必须提供这些参数,如果它在其构造函数中又希望传递abc,则将由类C提供这些参数,依此类推。 A child class may chose to provide a value which has not been passed in the constructor though and therefore subsequent children would no longer need to provide this value. 子类可以选择提供一个尚未在构造函数中传递的值,因此后续子类将不再需要提供此值。

AFAIK, the constructor of A will be responsible for the initialisation of A's data members, as classes are constructed from the top down, or Base-before-Derived. AFA的构造函数AFAIK将负责A的数据成员的初始化,因为类是从上到下或先于先生成的。 This is why you can't use a pure virtual member function in a constructor, as the derived class in which it is defined has not been created yet. 这就是为什么不能在构造函数中使用纯虚拟成员函数的原因,因为尚未定义定义它的派生类。

Every constructor of every class constructs all the immediate non-virtual base classes. 每个类的每个构造函数都构造所有直接的非虚拟基类。 That explains recursively what happens in your setup. 这就递归地解释了您的设置中发生的情况。

By contrast, virtual base classes are constructed by the constructor of the most-derived class. 相比之下,虚拟基类是由派生最多的类的构造函数构造的。

Here's a typical example which mentions the base constructors explicitly: 这是一个典型的示例,其中明确提到了基本构造函数:

struct A { A(int, int) { /* ... */ ; };

struct B : A { B(char, bool) : A(2, 3) { /* ... */ };

struct C : B { C() : B('x', false) { /* ... */ };

C c;  // calls A::A(2, 3), then B::B('x', false), then C::C()

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

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