简体   繁体   English

inheritance 和 c++ 中的初始化程序列表

[英]inheritance and initializer list in c++

类三角形

As seen in the picture above: class Triangle inherits from class Shape but why is there written Shape() in the initializer list and what happens if I leave it out?如上图所示: class Triangle 继承自 class Shape 但是为什么在初始化列表中写了 Shape() ,如果我把它排除在外会怎样?

if you don't put it it will still invoke the default parent class constructor anyway.如果你不说它仍然会调用默认的父 class 构造函数。 Putting it explicitly like this can be necessary if the parent constructor has keyword "explicit" however, or if there is no default parent constructor so you need to pass parameters to it..但是,如果父构造函数具有关键字“explicit”,或者如果没有默认父构造函数因此您需要将参数传递给它,则可能需要像这样显式放置它。

Your derived Triangle class looks like this:您派生的Triangle class 如下所示:

class Triangle : public Shape {
  Point _x1, _x2, _x3;
public:
  Triangle(const Point& x1, const Point& x2, const Point& x3)
    : Shape(), _x1(x1), _x2(x2), _x3(x3)
  {}
};

The base class, Shape , has its own default constructor which "does stuff".基础 class Shape有自己的默认构造函数“做事”。 It's not important what that is, really;实际上,那是什么并不重要; you just want to make sure that Shape 's constructor does get called so it can do whatever it needs to do during construction/initialization.您只想确保Shape的构造函数确实被调用,以便它可以在构造/初始化期间执行它需要执行的任何操作。 That might be setting some initial values, logging some debugging information to the console, or calling the constructor of its own parent class (if it has one).这可能是设置一些初始值,将一些调试信息记录到控制台,或者调用它自己的父 class 的构造函数(如果有的话)。

Therefore, when Triangle is constructed, it needs to explicitly tell its base class Shape to construct, too.因此,在构造Triangle时,也需要明确地告诉它的基础 class Shape来构造。

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

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