1.派生类构造函数的一般形式为:

派生类构造函数名(总参数表):基类构造函数名(参数表)

{

   派生类中新增加数据成员初始化语句

}

2.在建立一个对象时,执行构造函数的顺序是:

a.派生类构造函数先调用基类构造函数;

b.再执行派生类构造函数本身(即派生类构造函数的函数体)

3.在派生类对象释放时,先执行派生类析构函数,再执行其基类析构函数

例:定义一个简单的派生类构造函数。

解:程序:

#include<iostream>

#include<string>

using namespace std;

class Student//声明一个基类Student

{

public:

Student(int n, string nam, char s)//定义基类构造函数

{

num = n;

name = nam;

sex = s;

}

~Student()//基类析构函数

{

}

protected:

int num; 

string name;

char sex;

};


class Student1 :public Student//声明公用派生类Student1

{

public:

Student1(int n, string nam, char s, int a, string ad) :Student(n, nam, s)//定义派生类构造函数

{

age = a;//在函数体中只对派生类新增加的数据成员初始化

addr = ad;

}

void show()

{

cout << "num:" << num << endl;

cout << "name:" << name << endl;

cout << "sex:" << sex << endl;

cout << "age:" << age << endl;

cout << "address:" << addr << endl << endl;

}

~Student1()//派生类析构函数

{}

private:

int age;

string addr;

};


int main()

{

Student1 stud1(1001, "yaoyao", 'f', 20, "hanzhong");

Student1 stud2(1002, "xiaoxiao", 'm', 20, "xianyang");

stud1.show();//输出第一个学生数据

stud2.show();//输出第二个学生数据

system("pause");

return 0;

}


结果:

num:1001

name:yaoyao

sex:f

age:20

address:hanzhong

 

num:1002

name:xiaoxiao

sex:m

age:20

address:xianyang

 

请按任意键继续. . .