在 C++ 中,我们使用子类 继承 父类时,当实例化子类时,一定会优先调用父类的 构造函数,事实上,通过派生类创建对象时必须要调用基类的构造函数,这是语法规定。
换句话说,定义派生类构造函数时最好指明基类构造函数;如果不指明,就调用基类的默认构造函数(不带参数的构造函数);如果没有默认构造函数,那么编译失败。
子类继承父类时,实例化子类,会优先调用父类构造函数
#include <iostream>
using namespace std;
//人类
class Person
{
public:
Person()
{
cout << "Call Person" << endl;
}
};
//学生类
class Student : public Person
{
public:
Student()
{
cout << "Call Student" << endl;
}
};
int main(void)
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu;
return 0;
}
程序运行后,控制台输出如下:
从以上案例可以看出,我们在实例化子类 Student 时,首先调用了父类的构造函数,接着调用了子类的构造函数。因此,我们可以看出,在实例化子类时,会首先调用父类的构造函数,接着,会调用子类的构造函数。
子类继承父类时,实例化子类,会优先调用父类构造函数
#include <iostream>
using namespace std;
//人类
class Person
{
public:
Person()
{
cout << "Call Person" << endl;
}
};
//学生类
class Student : public Person
{
public:
Student()
{
cout << "Call Student" << endl;
}
};
class HighSchoolStudent : public Student
{
public:
HighSchoolStudent()
{
cout << "Call HighSchoolStudent" << endl;
}
};
int main(void)
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
HighSchoolStudent stu;
return 0;
}
程序运行后,控制台输出如下:
我们可以看出,当我们的继承有多级关系时,会优先调用最顶层的基类,接着一层一层的往下调用,一直调用到当前实例化的子类的构造函数。
子类继承父类时,实例化子类,如果不知道基类构造函数,则使用默认构造函数,如果没有,则报错
#include <iostream>
#include <string>
using namespace std;
//人类
class Person
{
public:
Person(string name)
{
}
};
//学生类
class Student : public Person
{
public:
Student()
{
cout << "Call Student" << endl;
}
};
int main(void)
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu;
return 0;
}
程序运行后,控制台输出如下:
我们在使用 Student 继承 Person 时,没有指定使用的构造函数,这时候,会自动调用 Person 类的构造函数,但因为,我们在 Person 类里面自定义了带参数的构造函数,因此,此时没有默认的构造函数了。
运行程序报错,因为,子类没有显式指定构造函数,那么会调用父类的默认构造函数。
在 C++ 中,我们使用子类继承父类时,当实例化子类时,一定会优先调用父类的构造函数,事实上,通过派生类创建对象时必须要调用基类的构造函数,这是语法规定。