網頁

2022/8/18

C++ 多態 polymorphism

C++的多態(polymorphism)為繼承類別間的特性,即衍生類別(derived class)的指標型態可相容於基底類別(base class)的指標型態。


例如下面的類別CarBoat繼承了Vehicle類別,則CarBoat的物件指標可分派至Vehicle的指標變數,不過其背後實際物件仍為其衍生類別,只是以基底類別的樣貌呈現,此即為polymorphism。

main.cpp

#include <iostream>
#include <string>
using namespace std;

class Vehicle {
    protected:
        int speed;

    public:
        Vehicle(int speed) : speed(speed) {}

        int GetSpeed() { return speed; }
};

class Car : public Vehicle {
    private:
        string wheelSize;

    public:
        Car(int speed, string wheelSize) : Vehicle(speed), wheelSize(wheelSize){};

        string GetWheelSize() { return wheelSize; }
};

class Boat : public Vehicle {
    private:
        string paddleSize;

    public:
        Boat(int speed, string paddleSize) : Vehicle(speed), paddleSize(paddleSize){};

        string GetPaddleSize() { return paddleSize; }
};

int main() {
    Car car = {100, "15 inch"};
    Vehicle *v1 = &car;
    cout << v1->GetSpeed() << endl;     // 100
    cout << car.GetWheelSize() << endl; // 15 inch

    Boat boat = {80, "200 cm"};
    Vehicle *v2 = &boat;
    cout << v2->GetSpeed() << endl;       // 80
    cout << boat.GetPaddleSize() << endl; // 200 cm

    return 0;
}

一旦衍生類別的指標轉為基底類別的指標後,則基底類別的指標僅能操作自身的成員而無法操作衍生類別的成員,例如上面Vehicle的指標v1v2無法存取來源衍生類別的成員屬性及方法。


沒有留言:

張貼留言