从哲学层面来看,子类会继承父类除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()即使不显示调用,实际上也会被调用。并且调用顺序优先于子类本身的构造函数。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有