Skip to main content

Command Palette

Search for a command to run...

一邊寫 C++ Class 一邊了解 OOP 4 個概念

Updated
2 min read

四個概念

抽象(Abstraction)

Abstraction is selective ignorance.

– Andrew Koenig

從沒有任何 code 到生出一個 Car 的 class,我們想把車子抽象出以下東西:

  • move(double t): 移動 t 秒

所以可以寫出這樣的 class

struct Car final {
    Car() = default;
    ~Car() = default;

    void move(double t) {
        // 這行計算不算在抽象部分
        x_ += speed_ * t;
    }

    double x_ = 0;
    double speed_ = 60;
};

封裝(Encapsulation)

確保物件狀態良好。

假如我們不希望使用者隨意調整車子的速度和位置,那我們要把他 private 起來,並且,我們不希望 move 的時間是可以倒流的

class Car final {
public:
    Car() = default;
    ~Car() = default;

    void move(double t) {
        if (t < 0) {
            throw std::runtime_error("t is negative");
        }
        x_ += speed_ * t;
    }

private:
    double x_ = 0;
    double speed_ = 60;
};

繼承(Inheritance)

Car2 是一種 Car

class Car {
public:
    Car() = default;
    virtual ~Car() = default;
    // ...
};

struct Car2 : public Car {
};

多型(Polymorphism)

CarLazy 是一種 Car ,並且他會偷懶,只用一半的速度移動。

class Car {
public:
    Car() = default;
    virtual ~Car() = default;

    virtual void move(double t) {
        if (t < 0) {
            throw std::runtime_error("t is negative");
        }
        x_ += speed_ * t;
    }

// 給繼承人使用
protected:
    double x_ = 0;
    double speed_ = 60;
};

class CarLazy : public Car {
public:
    void move(double t) override {
        if (t < 0) {
            throw std::runtime_error("t is negative");
        }
        x_ += speed_ * t / 2;
    }
};

參考

More from this blog

簡介 C++ 的 Type Erase (用多型和模板做 Duck Type)

起點 讓我們先從 template 出發:foo 需要一個 callback function。 template<typename Func> void foo(Func callback) { // ... callback(); } 但是這會讓編譯錯誤訊息有點模糊:假如 callback 並不是一個可以呼叫的函數指標,或者並不是一個 callable object ,那編譯器會說錯出在第四行。但是我們都希望,編譯器在呼叫函數時就幫我們指出:這不是 foo 想要的 call...

May 14, 20243 min read

帕秋莉的魔法筆記

45 posts

後端工程師。

不定時張貼一些寫扣時的筆記。