您好,登錄后才能下訂單哦!
1.派生類構(gòu)造函數(shù)的一般形式為:
派生類構(gòu)造函數(shù)名(總參數(shù)表):基類構(gòu)造函數(shù)名(參數(shù)表)
{
派生類中新增加數(shù)據(jù)成員初始化語句
}
2.在建立一個對象時,執(zhí)行構(gòu)造函數(shù)的順序是:
a.派生類構(gòu)造函數(shù)先調(diào)用基類構(gòu)造函數(shù);
b.再執(zhí)行派生類構(gòu)造函數(shù)本身(即派生類構(gòu)造函數(shù)的函數(shù)體)
3.在派生類對象釋放時,先執(zhí)行派生類析構(gòu)函數(shù),再執(zhí)行其基類析構(gòu)函數(shù)
例:定義一個簡單的派生類構(gòu)造函數(shù)。
解:程序:
#include<iostream>
#include<string>
using namespace std;
class Student//聲明一個基類Student
{
public:
Student(int n, string nam, char s)//定義基類構(gòu)造函數(shù)
{
num = n;
name = nam;
sex = s;
}
~Student()//基類析構(gòu)函數(shù)
{
}
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)//定義派生類構(gòu)造函數(shù)
{
age = a;//在函數(shù)體中只對派生類新增加的數(shù)據(jù)成員初始化
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()//派生類析構(gòu)函數(shù)
{}
private:
int age;
string addr;
};
int main()
{
Student1 stud1(1001, "yaoyao", 'f', 20, "hanzhong");
Student1 stud2(1002, "xiaoxiao", 'm', 20, "xianyang");
stud1.show();//輸出第一個學(xué)生數(shù)據(jù)
stud2.show();//輸出第二個學(xué)生數(shù)據(jù)
system("pause");
return 0;
}
結(jié)果:
num:1001
name:yaoyao
sex:f
age:20
address:hanzhong
num:1002
name:xiaoxiao
sex:m
age:20
address:xianyang
請按任意鍵繼續(xù). . .
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。