1. 程式人生 > >派生類建構函式的定義和使用舉例

派生類建構函式的定義和使用舉例

               


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

           

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://blog.csdn.net/jiangjunshow