C++構(gòu)造函數(shù)如何處理繼承關(guān)系

c++
小樊
81
2024-11-09 00:38:28

在C++中,構(gòu)造函數(shù)處理繼承關(guān)系的方式與類成員初始化列表類似。當(dāng)創(chuàng)建一個(gè)派生類對(duì)象時(shí),首先會(huì)調(diào)用基類的構(gòu)造函數(shù)來(lái)初始化基類部分,然后調(diào)用派生類自己的構(gòu)造函數(shù)來(lái)初始化派生類部分。這里有一個(gè)簡(jiǎn)單的例子來(lái)說(shuō)明構(gòu)造函數(shù)如何處理繼承關(guān)系:

#include <iostream>

class Base {
public:
    Base() {
        std::cout << "Base constructor called" << std::endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        std::cout << "Derived constructor called" << std::endl;
    }
};

int main() {
    Derived d; // 調(diào)用基類構(gòu)造函數(shù)和派生類構(gòu)造函數(shù)
    return 0;
}

在這個(gè)例子中,當(dāng)我們創(chuàng)建一個(gè)Derived類對(duì)象時(shí),首先會(huì)調(diào)用Base類的構(gòu)造函數(shù)來(lái)初始化基類部分,然后調(diào)用Derived類的構(gòu)造函數(shù)來(lái)初始化派生類部分。輸出結(jié)果如下:

Base constructor called
Derived constructor called

需要注意的是,如果基類沒(méi)有默認(rèn)構(gòu)造函數(shù)(即沒(méi)有參數(shù)的構(gòu)造函數(shù)),那么在創(chuàng)建派生類對(duì)象時(shí),必須顯式地調(diào)用基類的帶參數(shù)的構(gòu)造函數(shù),并將派生類構(gòu)造函數(shù)的參數(shù)傳遞給基類構(gòu)造函數(shù)。例如:

class Base {
public:
    Base(int x) {
        std::cout << "Base constructor called with value: "<< x << std::endl;
    }
};

class Derived : public Base {
public:
    Derived(int x, int y) : Base(x) { // 顯式調(diào)用基類構(gòu)造函數(shù)
        std::cout << "Derived constructor called with values: "<< x << ", "<< y << std::endl;
    }
};

int main() {
    Derived d(1, 2); // 調(diào)用基類構(gòu)造函數(shù)和派生類構(gòu)造函數(shù)
    return 0;
}

在這個(gè)例子中,Derived類顯式地調(diào)用了Base類的構(gòu)造函數(shù),并將x參數(shù)傳遞給基類構(gòu)造函數(shù)。輸出結(jié)果如下:

Base constructor called with value: 1
Derived constructor called with values: 1, 2

0