單一繼承多次與多重繼承的構造與析構
單一繼承多次
代碼:
class great_great_father { public: great_great_father() { cout << "function: \tgreat_great_father()" << std::endl; } ~great_great_father() { cout << "function: \t~great_great_father()" << std::endl; } }; class great_father : public great_great_father { public: great_father() { cout << "function: \tgreat_father()" << std::endl; } ~great_father() { cout << "function: \t~great_father()" << std::endl; } }; class father : public great_father { public: father() { cout << "function: \tfather()" << std::endl; } ~father() { cout << "function: \t~father()" << std::endl; } }; class son : public father { public: son() { cout << "function: \tson()" << std::endl; } ~son() { cout << "function: \t~son()" << std::endl; } }; int main(int argc, char *argv[]) { { son s; } system("pause"); return 0; }
son s;語句放在代碼塊里,使得析構放在主函數結束前。
類圖如下

運行結果:

多重繼承
代碼:
class father1 { public: father1() { cout << "function: \tfather1()" << std::endl; } ~father1() { cout << "function: \t~father1()" << std::endl; } }; class father2 { public: father2() { cout << "function: \tfather2()" << std::endl; } ~father2() { cout << "function: \t~father2()" << std::endl; } }; class father3 { public: father3() { cout << "function: \tfather3()" << std::endl; } ~father3() { cout << "function: \t~father3()" << std::endl; } }; class son : public father1, public father2, public father3 { public: son() { cout << "function: \tson()" << std::endl; } ~son() { cout << "function: \t~son()" << std::endl; } }; int main(int argc, char *argv[]) { { son s; } system("pause"); return 0; }
類圖:

運行結果:

編譯器:Visual Studio 2015 -> cl.exe
實踐很有意思!

浙公網安備 33010602011771號