基类构造函数自动调用
在C++中,当子类派生自一个基类时,基类的构造函数会自动调用。以下是示例代码:
#include
using namespace std;
class BaseClass {
public:
BaseClass() {
cout << "基类构造函数被调用" << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {
cout << "子类构造函数被调用" << endl;
}
};
int main() {
DerivedClass derived;
return 0;
}
输出:
基类构造函数被调用
子类构造函数被调用
在创建DerivedClass对象时,首先会自动调用基类的构造函数,然后再调用自己的构造函数。如果基类有参数化构造函数,子类的构造函数需要向基类构造函数传递参数,例如:
#include
using namespace std;
class BaseClass {
public:
BaseClass(int n) {
cout << "基类构造函数被调用,n=" << n << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass(int m, int n) : BaseClass(m) {
cout << "子类构造函数被调用,n=" << n << endl;
}
};
int main() {
DerivedClass derived(10, 20);
return 0;
}
输出:
基类构造函数被调用,n=10
子类构造函数被调用,n=20