子类的构造函数当中 参数列表应该含有 基类及子类的全部数据成员.
派生类的构造-析构顺序:
构造函数:先 基类 ;后子类;
析构函数:先 子类 ;后基类;
实例1:
// 派生类-构造函数.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class BaseEntity
{
protected:
int m1;
int m2;
public:
BaseEntity(int i,int j)
{
cout << "base class constructor." <<endl;
m1 = i;
m2 = j;
}
};
////
class Derived:public BaseEntity
{
private:
int m3;
int m4;
public:
Derived(int i,int j,int m,int n):BaseEntity(i,j)//注意i,j顺序..
{
cout <<"derived class constructor."<<endl;
m3 = m;
m4 = n;
}
void printMember()
{
cout<<"m1: "<< m1 <<endl
<<"m2: "<< m2 <<endl
<<"m3: "<< m3 <<endl
<<"m4: "<< m4 <<endl;
}
};
////
int _tmain(int argc, _TCHAR* argv[])
{
Derived d(1,2,3,4);
d.printMember();
getchar();
return 0;
}
实例2:
// 派生类-析构函数.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class BaseEntity
{
public:
BaseEntity()
{
cout<<"base class constructor." <<endl;
}
~BaseEntity()
{
cout<<"base class destructor." <<endl;
}
};
///
class Derived:public BaseEntity
{
public:
Derived()
{
cout<<"derived class constructor." <<endl;
}
~Derived()
{
cout<<"derived class destructor." <<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derived d;
// getchar();
return 0;
}