有继承情形下 基类与子类的构造函数与析构函数运行顺序,如下代码:
#include "stdafx.h"
#include
using namespace std;
class A {
public:
A() {
cout << "Base class constructor" << endl;
}
~A() {
cout << "Base class destructor" << endl;
}
};
class B : public A {
public:
B() {
cout << "Subclass constructor" << endl;
}
~B() {
cout << "Subclass Destructor" << endl;
}
};
void function() {
B b;
}
int main()
{
function();
while (1);
return 0;
}
试运行代码查看结果,而知基类与子类构造函数与析构函数的顺序。
注:在派生类中,若基类构造函数含有参数(有关内容可参考我的博客或网上其它解释),则必须有子类构造函数且说明基类构造函数,其代码如下:
#include "stdafx.h"
#include
#include
#include
using namespace std;
class A {
public:
A(int c) {
cout << "c=" <<c<< endl;
} //此为含参构造函数
~A() {
cout << "come on" << endl;
}
public:
int c;
};
class B : public A {
public:
B(int c ,int b):A(c) {
cout << "b="<<b<< endl;
} //此为子类含参构造函数
~B() {
cout << "Subclass Destructor" << endl;
}
private:
int b;
};
int main()
{
B bb(10,100); //此种用法相关解释,可见我的博客
while (1);
return 0;
}
仔细比较下一个代码与上一个代码:
#include "stdafx.h"
#include
#include
#include
using namespace std;
class A {
public:
A(int c) {
cout << "c=" <<c<< endl;
} //此为含参构造函数
~A() {
cout << "come on" << endl;
}
public:
int c;
};
class B : public A {
public:
B(int c ,int b); //此为子类含参构造函数
~B() {
cout << "Subclass Destructor" << endl;
}
private:
int b;
};
B::B(int c ,int b):A(c) {
cout << "b="<<b<< endl;
} //类外写函数,A(c)表示调用基类构造函数,故而无数据类型
int main()
{
B bb(10,100); //此种用法相关解释,可见我的博客
while (1);
return 0;
}
点亮希望!