AdSense

網頁

2022/8/24

C++ 虛擬函式 virtual functions

C++ 在類別函式(方法)前加上virtual關鍵字則為虛擬函式(virtual function)。


虛擬函式為基底類別(base class)的函式,而繼承基底類別的衍生類別(derived class)則可覆寫(override)虛擬函式,若衍生類別未覆寫虛擬函式則呼叫基底類別虛擬函式的實作,即衍生類別的預設函式實作。

例如下面的類別CarBoat繼承了Vehicle類別。基底類別Vehicle的函式GetSpeed()前有virtual為虛擬函式。

Car重新定義GetSpeed()的實作因此覆寫了VehicleGetSpeed()Boat則未覆寫VehicleGetSpeed()。執行時Vehicle多態物件v1實為Car呼叫自身GetSpeed();而v2實為Boat呼叫的是VehicleGetSpeed()

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;
}


沒有留言:

AdSense