将参数传递给超类构造函数 [英] Passing arguments to a superclass constructor

查看:73
本文介绍了将参数传递给超类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入派生类,并且正在研究著名的 Shape 类。 Shape 是基类,然后我有三个派生类: Circle Rectangle Square Square Rectangle 的派生类。我认为我需要将参数从派生类构造函数传递给基类构造函数,但是我不确定到底该怎么做。我想在创建形状时设置形状的尺寸。这是我对基类和一个派生类所拥有的:

I'm just getting into derived classes, and I'm working on the famous Shape class. Shape is the base class, then I have three derived classes: Circle, Rectangle, and Square. Square is a derived class of Rectangle. I think I need to pass arguments from the derived class constructors to the base class constructor, but I'm not sure exactly how to do this. I want to set the dimensions for the shapes as I create them. Here is what I have for the base class and one derived class:

Shape(double w = 0, double h = 0, double r = 0)
{
     width = w;
     height = h;
     radius = r;
}


class Rectangle : public Shape
{
     public:
     Rectangle(double w, double h) : Shape(double w, double h)
     {
         width = w;
         height = h;
     }              
     double area();
     void display();      
};

我在这里吗?我收到以下编译器错误:在每个派生构造函数中,在 double之前预期的主表达式

Am I on the right track here? I'm getting the following compiler error: expected primary expression before "double", in each of the derived constructors.

推荐答案

您必须将 Shape(double w,double h)更改为 Shape(w,h) 。您实际上是在这里调用基本构造函数。

You have to change Shape(double w, double h) to Shape(w, h). You are actually calling the base constructor here.

此外,您不必设置 width height 在派生类的构造函数主体中:

In addition, You don't have to set width and height in the constructor body of the derived class:

  Rectangle(double w, double h) : Shape(w, h)
  {}

就足够了。这是因为在您的初始化器列表中, Shape(w,h)将调用基类的构造函数( shape ) ,这将为您设置这些值。

is enough. This is because in your initializer list Shape(w, h) will call the constructor of the base class (shape), which will set these values for you.

创建派生对象时,将执行以下操作:

When a derived object is created, the following will be executed:


  1. Shape 留出内存空间

  2. 适当的Base构造函数称为

  3. 初始化列表初始化变量

  4. 构造函数的主体执行

  5. 控制权返回给调用者

  1. Memory for Shape is set aside
  2. The appropriate Base constructor is called
  3. The initialization list initializes variables
  4. The body of the constructor executes
  5. Control is returned to the caller

在您的示例中, Shape 子对象由 Shape(double w = 0,double h = 0,double r = 0)。在此过程中,基本部分的所有成员(宽度高度半径)由基本构造函数初始化。之后,将执行派生构造函数的主体,但是您不必在这里进行任何更改,因为所有这些都由基本构造函数负责。

In your example, the Shape subobject is initialized by Shape(double w = 0, double h = 0, double r = 0). In this process, all the members of the base part (width, height, radius) are initialized by the base constructor. After that, the body of the derived constructor is executed, but you don't have to change anything here since all of them are taken care of by the base constructor.

这篇关于将参数传递给超类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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