C ++调用基类构造函数 [英] C++ calling base class constructors

查看:289
本文介绍了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 ++调用基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆