瞭解一個概念:動態綁定和靜態綁定:ios
下面看一段代碼:函數
#include <iostream> using namespace std; class Parent { public: void virtual foo() { cout << "foo from parent!\n"; } void foo1() { cout << "foo1 from parent!\n"; } }; class Son : public Parent { public: void foo() { cout << "foo from son!\n"; } void foo1() { cout << "foo1 from son!\n"; } }; int main() { Parent *p = new Son; p->foo(); p->foo1(); return 0; }
運行以後,結果是:spa
foo from son!這是由於,編譯器在遇到irtual函數時,採用動態綁定,這麼講吧,指針
對於重載的virtual函數,調用哪一個函數是根據對象來決定的,這是在函數運行的動態過程當中完成的。code
對於非virtual函數,調用哪一個函數是根據指針類型來決定的:編譯器根據指針的類型靜態的決定出來,這是靜態綁定。對象
在C++中,函數默認的是靜態綁定。ip
下面看一個經典用法:編譯器
// dscombine_poly.h #include <iostream> #include <vector> // 公共抽象基類Vehicle class Vehicle { public: virtual void run() const = 0; }; // 派生於Vehicle的具體類Car class Car: public Vehicle { public: virtual void run() const { std::cout << "run a car/n"; } }; // 派生於Vehicle的具體類Airplane class Airplane: public Vehicle { public: virtual void run() const { std::cout << "run a airplane/n"; } void add_oil() const { std::cout << "add oil to airplane/n"; } }; // 派生於Vehicle的具體類Airship class Airship: public Vehicle { public: virtual void run() const { std::cout << "run a airship/n"; } void add_oil() const { std::cout << "add oil to airship/n"; } }; // dscombine_poly.cpp #include <iostream> #include <vector> //#include "dscombine_poly.h" // run異質vehicles集合 void run_vehicles(const std::vector<Vehicle*>& vehicles)//指針類型是vehicle,若是非virtual函數,則根據 //指針類型來決定調用哪一個函數,但此時是virtual的,因此動態綁定,根據調用對象來抉擇 { for (unsigned int i = 0; i < vehicles.size(); ++i) { vehicles[i]->run(); // 根據具體的vehicle類型調用對應的run() } } // 爲某種特定的aircrafts同質對象集合進行「空中加油」 template <typename Aircraft>//模板,定義一個Aircraft類型,作爲函數參數類型的集合,那麼函數參數中,具體的就能夠是任何類型 void add_oil_to_aircrafts_in_the_sky(const std::vector<Aircraft>& aircrafts) {//這個無論是irtual仍是非irtual,都是使用對象類型(指針類型)來選擇 for (unsigned int i = 0; i < aircrafts.size(); ++i) { aircrafts[i].add_oil(); } } int main() { Car car1, car2; Airplane airplane1, airplane2; Airship airship1, airship2; std::vector<Vehicle*> v; // 異質vehicles集合 v.push_back(&car1); v.push_back(&airplane1); v.push_back(&airship1); run_vehicles(v); // run不一樣種類的vehicles std::vector<Airplane> vp; // 同質airplanes集合 vp.push_back(airplane1); vp.push_back(airplane2); add_oil_to_aircrafts_in_the_sky(vp); // 爲airplanes進行「空中加油」 std::vector<Airship> vs; // 同質airships集合 vs.push_back(airship1); vs.push_back(airship2); add_oil_to_aircrafts_in_the_sky(vs); // 爲airships進行「空中加油」 }