1. 程式人生 > 其它 >繼承和派生(2)--繼承中對建構函式、同名函式的處理方式

繼承和派生(2)--繼承中對建構函式、同名函式的處理方式

技術標籤:# 繼承和派生c++繼承

繼承和派生--繼承中對建構函式、同名函式的處理方式

1 繼承中的構造和析構

先呼叫父類構造,再呼叫其他成員構造(其他類作為派生類的成員),再呼叫自身構造 ,析構的順序與構造相反。

#include <iostream>
using namespace std;

 // 基類
class Base
{
public:
    Base()
    {   
        cout << "Base構造" << endl;
} ~Base() { cout << "Base析構" << endl; } }; // 其他類 class Other { public: Other() { cout << "Other構造" << endl; } ~Other() { cout << "Other析構" << endl; } }; // 派生類
class Derive : public Base { public: Derive() { cout << "Derive構造" << endl; } ~Derive() { cout << "Derive析構" << endl; } Other other; // 其他類作為派生類的成員 }; int main() { Derive derive; return 0; }

structure



2 繼承中的同名成員處理

當子類重新定義了父類中的同名成員函式,子類的成員函式會隱藏掉父類中所有過載版本的同名成員,可以利用作用域顯示指定呼叫。

#include <iostream>
using namespace std;

class Base
{
public:
    void showAge()
    {   
        cout << "Base::m_Age = " << m_Age << endl;
    }   
    int m_Age;
};

class Derive : public Base
{
public:
    void showAge()
    {   
        cout << "Derive::m_Age = " << m_Age << endl;
    }   
    int m_Age;
};

int main()
{
    Derive derive;

    derive.m_Age = 10; 
    derive.showAge();

	// 利用作用域訪問父類中的同名成員
    derive.Base::m_Age = 20; 
    derive.Base::showAge();
        
    return 0;
}

在這裡插入圖片描述



3 繼承中的同名靜態成員處理

當子類重新定義了父類中的同名成員函式,子類的成員函式會隱藏掉父類中所有過載版本的同名成員,可以利用作用域顯示指定呼叫。(結論與同名普通成員一致,只不過呼叫方式有兩種:1.通過物件,2.通過類名)

#include <iostream>
using namespace std;

class Base
{
public:
    static void showAge()
    {   
        cout << "Base::m_Age = " << m_Age << endl;
    }
    static int m_Age; // 類內宣告
};
int Base::m_Age = 18;   // 類外初始化
           
class Derive : public Base
{          
public:    
    void showAge()
    {      
        cout << "Derive::m_Age = " << m_Age << endl;
    }      
    int m_Age;
};         
           
int main() 
{          
    Derive derive;
           
    derive.m_Age = 10;
    derive.showAge();
           
    // 1.通過物件訪問
    derive.Base::m_Age = 20; 
    derive.Base::showAge();

    // 2.通過類名訪問
    Derive::Base::m_Age = 30;
    Derive::Base::showAge();

    return 0;
}