C ++调用基类构造函数

编程入门 行业动态 更新时间:2024-10-22 14:04:35
本文介绍了C ++调用基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <iostream> #include <stdio.h> using namespace std; // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } Shape() { printf("creating shape \n"); } Shape(int h,int w) { height = h; width = w; printf("creatig shape with attributes\n"); } protected: int width; int height; }; // Derived class class Rectangle: public Shape { public: int getArea() { return (width * height); } Rectangle() { printf("creating rectangle \n"); } Rectangle(int h,int w) { printf("creating rectangle with attributes \n"); height = h; width = w; } }; int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); Rectangle *square = new Rectangle(5,5); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; return 0; }

程序的输出如下:

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 ++调用基类构造函数

本文发布于:2023-10-31 07:35:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545452.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!