在C ++中,我们可以派生一些类。有时,在调用派生类的构造函数时,需要调用超类(基类)的构造函数。与Java不同,超类没有引用变量。如果构造函数是非参数化的,那么它将被派生类自动调用,否则我们必须将超类构造函数放在派生类的初始化列表中。
首先,在此示例中,我们将看到没有参数的构造函数。
#include <iostream> using namespace std; class MyBaseClass { public: MyBaseClass() { cout << "Constructor of base class" << endl; } }; class MyDerivedClass : public MyBaseClass { public: MyDerivedClass() { cout << "Constructor of derived class" << endl; } }; int main() { MyDerivedClass derived; }
输出结果
Constructor of base class Constructor of derived class
现在让我们看一下可以接受参数的构造函数。
#include <iostream> using namespace std; class MyBaseClass { public: MyBaseClass(int x) { cout << "Constructor of base class: " << x << endl; } }; class MyDerivedClass : public MyBaseClass { //base constructor as initializer list public: MyDerivedClass(int y) : MyBaseClass(50) { cout << "Constructor of derived class: " << y << endl; } }; int main() { MyDerivedClass derived(100); }
输出结果
Constructor of base class: 50 Constructor of derived class: 100