派生类构造函数的定义和使用举例


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

 

请按任意键继续. . .

 


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1763588

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值