程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++語言筆記系列之十五——派生類、基類、子對象的構造和析構函數調用關系

C++語言筆記系列之十五——派生類、基類、子對象的構造和析構函數調用關系

編輯:C++入門知識

例子
example 1
注:若一個基類同時派生出兩個派生類,即兩個派生類從同一個基類繼承,那麼系統將為每一個簡歷副本,每個派生類獨立地使用自己的基類副本(比如基類中有屬於自己類的靜態變量等)。
#include

class Person
{
public:
person() {cout<<"Construction of person."< ~person() {cout<<"Destruction of person."< };
class Student:public person
{
public:
student() {cout<<"Construction of student."< ~student() {cout<<"Destruction of student."< };
class Teacher:public Person
{
public:
Teacher() {cout<<"Construction of teacher."< ~Teacher() {cout<<"Destruction of teacher."< };

int main()
{
Student s;
Teacher t;
}
程序輸出:
Construction of person.
Construction of student.
Construction of person.
Construction of teacher.
Destruction of teacher.
Destruction of person.
Destruction of student.
Destruction of person.
結論:若一個程序中有多個對象,每個對象必須按照順序創建,在創建派生類對象時,調用構造函數的順序為:基類構造-->子對象構造-->派生類構造。析構函數的調用順序嚴格與構造函數相反。在派生類的構造函數中,當基類的構造函數缺省參數時,在派生類構造函數中可以缺省對基類構造函數的調用。

example 2

#include
class Data
{
public:
Data(int x) {Data::x = x; cout<<"Data construction."< ~Data() {cout<<"Data destruction."< private:
int x;
};
class Base
{
public:
Base(int x):d1(x) {cout<<"Base construction."< ~Base() {cout<<"Base destruction."< private:
Data d1;
};
class Device:public Base
{
public:
Device(int x):Base(x), d2(x) //參數共用
{cout<<"Device construction."< ~Device() {cout<<"Device destruction."< private:
Data d2;
};

int main()
{
Device obj(5);
}
程序輸出:
Data construction.
Base construction.
Data construction.
Device construction.
Device destruction.
Data destruction.
Base destruction.
Data destruction.
構造順序分析:調用Base類構造,而Base中含有子對象d1,所以要先調用d1的構造函數再調用Base的構造函數;Base構造函數調用完成之後再調用d2的構造;最後一步是調用派生類的構造。

example 3

class Base
{
public:
Base(int xx = 0):x(xx) //注意沒有分號,等價於普通的構造函數類型
{cout<<"Base construction."< ~Base() {cout<<"Base destrcution."< void print() {cout< int Getx() {return x;}
private:
int x;
};
class Device:public Base
{
public:
Device(itn xx = 0, int yy = 0):Base(xx), y(yy), z(xx+yy)
{cout<<"Device construction."< ~Device() {cout<<"Device destruction."< void print()
{
Base::print();
cout< }
private:
int y;
Base z;
};
int main()
{
Device obj1(1), obj2(4, 6);
obj1.print();
obj2.print();
}
程序輸出:
Base construction.
Base construction.
Device construction.
Base construction.
Base construction.
Device construction.
2,0,2
4,6,10
析構略......

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved