简体   繁体   English

C ++继承:避免调用基类的默认构造函数

[英]C++ Inheritence: Avoid calling default constructor of base class

In the following code I am calculating the area of triangle. 在下面的代码中,我正在计算三角形的面积。 Once I declare the object tri1 the width and height are initialized twice. 一旦我声明了对象tri1,宽度和高度就会初始化两次。

First: The default constructor of the base class is called and values width = 10.9 ; 首先:调用基类的默认构造函数,其值width = 10.9 ; height = 8.0 ; height = 8.0 ; are automatically assigned to the triangle. 自动分配给三角形。

Then: In triangle construct width = a; 然后:在三角形中,width = a; and height = b; 和高度= b; happens. 发生。

But, my question is: Is there any way not to call any constructor from a base class? 但是,我的问题是:有没有办法不从基类中调用任何构造函数?

class polygon {
protected:
    float width, height;
public:
    polygon () {width = 10.9; height = 8.0;}
    void set_val (float a, float b) {width = a; height = b;}
    polygon (float a, float b) : width(a), height(b) {cout<<"I am the polygon"<<endl;}
};

class triangle: public polygon {
public:
    triangle (float a, float b) {cout<<"passed to polygon"<<endl; width = a; height = b;} 
    float area () {return width*height/2;}
};

int main () {
    triangle tri1 {10, 5};
    cout<<tri1.area()<<endl;
}

You're not doing anything in the derived constructor. 您没有在派生构造函数中做任何事情。 A derived class calls the default constructor of the base class implicitly and there's no way to avoid it. 派生类隐式调用基类的默认构造函数,无法避免。 Instead, you should delegate the derived constructor's parameters to the base one. 相反,您应该将派生的构造函数的参数委托给基本的参数。

First, a small problem. 首先,一个小问题。 Your code initialises the variables inside the constructor, in C++ we use initialisation lists like so: 您的代码在构造函数中初始化变量,在C ++中,我们使用初始化列表,如下所示:

class polygon {
protected:
    float width, height;
public:
    polygon(): width(10.9), height(8.0) {}
    void set_val (float a, float b) {width = a; height = b;}
    polygon (float a, float b) : width(a), height(b) {cout<<"I am the polygon"<<endl;}
};

On to the real problem; 处理真正的问题; To fix your issue, make the derived class call the base constructor explicitly: 要解决您的问题,请使派生类显式调用基本构造函数:

class triangle: public polygon {
public:
    triangle(float a, float b): polygon(a, b) {cout<<"passed to polygon"<<endl;}
    float area () {return width*height/2;}
};

After that, it should work properly. 之后,它应该可以正常工作。

No, you can't avoid calling a base class constructor. 不,您无法避免调用基类构造函数。 You can specify which base class constructor to call in derived class though by specifying the base class constructor in the initializer list of the derived class constructor and passing arguments to the constructor which match a base class constructor prototype. 尽管可以通过在派生类构造函数的初始化器列表中指定基类构造函数,然后将与基类构造函数原型匹配的参数传递给该构造函数,来指定在派生类中调用哪个基类构造函数。 From those arguments the base class constructor is deduced. 从这些参数推导出基类构造函数。

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

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