基类与派生的构造函数的调用顺序。创建时先基类后派生类。销毁时先派生类后基类。

 当有参数时,参数必须传送给基类。注意例子中传递的方法。



#include <iostream>
#include <string>
using namespace std;

class CBase {
string name;
public:
CBase(string s) : name(s) {
cout << "BASE: " << name << endl;
}
~CBase() {
cout << "~BASE" << endl;
}
};

class CDerive : public CBase {
int age;
public:
CDerive(string s, int a) : CBase(s), age(a) {
cout << "DERIVE: " << age << endl;
}
~CDerive() {
cout << "~DERIVE" << endl;
}
};

int main ( )
{
CDerive d("小雅", 27);

return 0;
}


输出;

BASE: 小雅

DERIVE: 27

~DERIVE

~BASE

请按任意键继续. . .

深入: