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

Ash*_*wal 1 c++

在下面的代码中,我正在计算三角形的面积。一旦我声明了对象 tri1,宽度和高度就会被初始化两次。

第一:基类的默认构造函数被调用和值width = 10.9height = 8.0; 被自动分配给三角形。

然后:在三角形中构造宽度 = a; 和高度= b; 发生。

但是,我的问题是:有没有办法不从基类调用任何构造函数?

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;
}
Run Code Online (Sandbox Code Playgroud)

Rap*_*ptz 5

你没有在派生的构造函数中做任何事情。派生类隐式调用基类的默认构造函数,并且无法避免它。相反,您应该将派生构造函数的参数委托给基本构造函数。

首先,一个小问题。您的代码初始化构造函数内的变量,在 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;}
};
Run Code Online (Sandbox Code Playgroud)

真正的问题; 要解决您的问题,请使派生类显式调用基构造函数:

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

之后,它应该可以正常工作。