程序的输出如下:
creating shape creating rectangle creating shape creating rectangle with attributes Total area: 35在构造两个派生类对象时,我发现它始终是默认情况下首先调用的基类构造函数。是否有一个原因?这就是为什么像python这样的语言坚持基类构造函数的显式调用而不是像C ++这样的隐式调用?
When constructing both the derived class objects I see that it is always by default the base class constructor that is called first. Is there a reason for this? Is this the reason why languages like python insist on explicit calls of base class constructors rather than implicit calls like C++?
推荐答案对此的回答是,因为这是C ++标准指定的内容。
The short answer for this is, "because that's what the C++ standard specifies".
请注意,您始终可以指定与默认值不同的构造函数,如下所示:
Note that you can always specify a constructor that's different from the default, like so:
class Shape { Shape() {...} //default constructor Shape(int h, int w) {....} //some custom constructor }; class Rectangle : public Shape { Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call }只有在你做的时候才会调用基类的默认构造函数指定要拨打哪一个。
The default constructor of the base class is called only if you don't specify which one to call.
更多推荐
C ++调用基类构造函数
发布评论