C++ 在類別函式(方法)前加上virtual
關鍵字則為虛擬函式(virtual function)。
虛擬函式為基底類別(base class)的函式,而繼承基底類別的衍生類別(derived class)則可覆寫(override)虛擬函式,若衍生類別未覆寫虛擬函式則呼叫基底類別虛擬函式的實作,即衍生類別的預設函式實作。
例如下面的類別Car
及Boat
繼承了Vehicle
類別。基底類別Vehicle
的函式GetSpeed()
前有virtual
為虛擬函式。
Car
重新定義GetSpeed()
的實作因此覆寫了Vehicle
的GetSpeed()
;Boat
則未覆寫Vehicle
的GetSpeed()
。執行時Vehicle
的多態物件v1
實為Car
呼叫自身GetSpeed()
;而v2
實為Boat
呼叫的是Vehicle
的GetSpeed()
。
main.cpp
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
protected:
int speed;
public:
Vehicle(int speed) : speed(speed) {}
virtual int GetSpeed() { return speed; }
};
class Car : public Vehicle {
public:
Car(int speed) : Vehicle(speed){};
int GetSpeed() { return speed + 10; }
};
class Boat : public Vehicle {
public:
Boat(int speed) : Vehicle(speed){};
};
int main() {
Car car = {100};
Vehicle *v1 = &car;
cout << v1->GetSpeed() << endl; // 110
Boat boat = {80};
Vehicle *v2 = &boat;
cout << v2->GetSpeed() << endl; // 80
return 0;
}
沒有留言:
張貼留言