小朋友学C++(10):子类构造函数调用父类构造函数

时间:2022-05-11
本文章向大家介绍小朋友学C++(10):子类构造函数调用父类构造函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

从哲学层面来看,子类会继承父类除private以外的所有成员。 因为构造函数是公有的,所以理所当然地会被子类继承。

程序1:

#include <iostream>
using namespace std;
class Shape
{
public:
    Shape() 
    {
        cout << "Shape's constructor method is invoked!n";
    }
};
class Rectangle : public Shape
{
public:
    Rectangle() : Shape()
    {
        cout << "Rectangle's constructor method is invoked!n" << endl;
    }
};
int main(int argc, char** argv) 
{
    Rectangle rec;
    return 0;   
}

运行结果:

Shape's constructor method is invoked!
Rectangle's constructor method is invoked!

分析: 这里构造函数的写法是 Rectangle() : Shape() { 子类构造函数本身的语句; } 这是先调用父类的构造函数,再执行它本身的语句。从运行结果也可以看出这一点。

那么,如果不显示调用父类的构造函数Shape()呢?父类的构造函数就不被调用了吗? 咱们可以用下面的程序来验证。

程序2:

#include <iostream>
using namespace std;
class Shape
{
public:
    Shape() 
    {
        cout << "Shape's constructor method is invoked!n";
    }
};
class Rectangle : public Shape
{
public:
    Rectangle()
    {
        cout << "Rectangle's constructor method is invoked!n" << endl;
    }
};
int main(int argc, char** argv) 
{
    Rectangle rec;
    return 0;   
}

运行结果:

Shape's constructor method is invoked!
Rectangle's constructor method is invoked!

分析: 从运行结果可以看出,程序1和程序2的运行结果完全一致。也就是说,Shape()即使不显示调用,实际上也会被调用。并且调用顺序优先于子类本身的构造函数。