由于派生类包含基类的原因,我们在创建一个派生类的时候,系统会先创建一个基类。需要注意的是,派生类会吸纳基类的全部成员,但并不包括构造函数及后面讲的析构函数,那么就意味着创建派生类在调用自己的构造函数之前,会先调用基类的构造函数。
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout << "This is Base constructor" << endl;
}
~Base(){
cout << "THis is Base discontructor" << endl;
}
Base(int n): num(n){}
void print(){
cout << "Hello Base class: " << num << endl;
}
private:
int num = 1;
};
class Derived : public Base{
public:
Derived(){
cout << "This is Derived constructor" << endl;
}
~Derived(){
cout << "THis is Derived disconstructor" << endl;
}
//基类如果有带参构造函数,那么派生类通过基类的构造函数
//来初始化它的基类部分
//首先初始化基类部分,然后再依次初始化它自己的部分
Derived(int n): Base(n), code(n){}
void greet(){
cout << "Hello, Derived class: " << code << endl;
}
private:
int code = 2;
};
int main(){
Derived A, B(10);
A.print();
A.greet();
B.print();
B.greet();
return 0;
}
运行结果: