Kodewick
開始學 →
虛擬函式和多型24 / 30

C++ 虛擬函式

第 24 課,共 30 課 · 第 6 部分 · 繼承和模板 · 約 25 分鐘

虛擬函式(virtual)讓基類指標呼叫到派生類自己的版本,這就是多型;有虛擬函式的基類,解構函式也要寫成虛擬函式。

上一課留了一個問題:通過基類的引用或指標,調到的是基類的函式,即使物件是改寫了這個函式的派生類。換成通知再看一遍:deliver 接收任何 Notification,交給它一封郵件和一條簡訊:

main.cpp
1#include <iostream>2 3class Notification {4public:5    void send() const {6        std::cout << "傳送一條通知\n";7    }8};9 10class Email : public Notification {11public:12    void send() const {13        std::cout << "傳送一封郵件\n";14    }15};16 17class TextMessage : public Notification {18public:19    void send() const {20        std::cout << "傳送一條簡訊\n";21    }22};23 24void deliver(const Notification& n) {25    n.send();26}27 28int main() {29    Email e;30    TextMessage t;31    deliver(e);32    deliver(t);33    return 0;34}
輸出
傳送一條通知
傳送一條通知

兩行都是「通知」。編譯器把 n.send() 變成程式碼的時候,只知道 n 是 Notification&,於是一次定死:呼叫 Notification::send。n 後面到底是什麼物件,要等程式跑起來才知道。

單選

這一關開頭的程式裡,為什麼 deliver(e) 顯示的也是通知?

virtual

在基類的函式前面加上 virtual,挑哪個版本就推遲到程式執行的時候:每次呼叫都看看物件本身,執行它那個類的版本。派生類那邊,在括號後面寫上 override:

main.cpp
1#include <iostream>2 3class Notification {4public:5    virtual void send() const {6        std::cout << "傳送一條通知\n";7    }8};9 10class Email : public Notification {11public:12    void send() const override {13        std::cout << "傳送一封郵件\n";14    }15};16 17class TextMessage : public Notification {18public:19    void send() const override {20        std::cout << "傳送一條簡訊\n";21    }22};23 24void deliver(const Notification& n) {25    n.send();26}27 28int main() {29    Email e;30    TextMessage t;31    deliver(e);32    deliver(t);33    return 0;34}
輸出
傳送一封郵件
傳送一條簡訊

只改了一個 virtual 和兩個 override,deliver 對每種通知都做對了。點單步:從 deliver 裡的 n.send() 出發,第一次進了 Email::send,第二次進了 TextMessage::send。同一行程式碼,看物件是什麼,每次執行不同的函式:這叫多型。

沒有 virtualvoid send() const傳送一條通知只看 n 是 Notification&
有 virtualvirtual void send() const傳送一封郵件看到物件是 Email
同樣是 deliver(e):沒有 virtual,編譯時只看 n 的型別;有 virtual,執行時看 n 後面真正的物件

基類裡是 virtual 的函式,到了每個派生類裡也都是虛擬函式,寫不寫這個詞都一樣。為了做到這一點,有虛擬函式的類的每個物件都帶著一個隱藏的指標,指向它那個類的版本表;單步畫面裡不顯示它。

只有通過引用或指標呼叫才看物件。複製出來的就是一個基類物件:

單選猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2 3class Notification {4public:5    virtual void send() const {6        std::cout << "通知\n";7    }8};9 10class Email : public Notification {11public:12    void send() const override {13        std::cout << "郵件\n";14    }15};16 17int main() {18    Email e;19    Notification copy = e;20    Notification& ref = e;21    copy.send();22    ref.send();23    return 0;24}

override

override 不是非寫不可,但每次都寫上。派生類的函式要每一樣都對上才能替換基類的虛擬函式:名字、引數,還有 const。漏了 const 就成了另一個函式,override 會把它抓出來:

main.cpp
1#include <iostream>2 3class Notification {4public:5    virtual void send() const {6        std::cout << "傳送一條通知\n";7    }8};9 10class Email : public Notification {11public:12    void send() override {13        std::cout << "傳送一封郵件\n";14    }15};16 17int main() {18    Email e;19    const Notification& n = e;20    n.send();21    return 0;22}
輸出
main.cpp:12:10: error: 'void Email::send()' marked 'override', but does not override
   12 |     void send() override {
      |          ^~~~

'void Email::send()' marked 'override', but does not override:基類裡沒有不帶 const 的 send() 可以替換。先看第一個 error:,意思是「它和基類裡的哪個都對不上」。加上 const 就編譯通過了。

不寫 override,同樣的錯能悄悄編譯通過:Email::send 成了一個新函式,只是把基類的隱藏了,通過 n 呼叫還是走到 Notification::send。這種錯很難找;override 把它變成編譯錯誤。

單選

基類裡是 virtual void send() const。派生類裡哪一個能替換它?

練習 1

修好它:沒對上的 override

這段程式編譯不過。先看第一個 error:,再改 Reminder,讓它真正替換 Message 的函式。程式要顯示下面兩行。

要顯示
小林,你好
老王,賬單該交了
exercise1.cpp
1#include <iostream>2#include <string>3 4class Message {5public:6    virtual ~Message() {}7 8    virtual std::string text(const std::string& name) const {9        return name + ",你好";10    }11};12 13class Reminder : public Message {14public:15    std::string text(std::string name) override {16        return name + ",賬單該交了";17    }18};19 20void show(const Message& m, const std::string& name) {21    std::cout << m.text(name) << '\n';22}23 24int main() {25    Message hello;26    Reminder bill;27    show(hello, "小林");28    show(bill, "老王");29    return 0;30}
輸出
點「執行」或按 Ctrl+Enter

一個 vector 裡放各種形狀

物件多了、類又各不相同的時候,多型最有用。把它們當基類指標放進同一個 vector,一個迴圈就全管了。std::unique_ptr(第 21 課)在 vector 死的時候把它們刪掉:

main.cpp
1#include <iostream>2#include <memory>3#include <string>4#include <vector>5 6class Shape {7public:8    virtual ~Shape() {}9 10    virtual double area() const {11        return 0;12    }13 14    virtual std::string name() const {15        return "形狀";16    }17};18 19class Rectangle : public Shape {20public:21    Rectangle(double w, double h) : w_(w), h_(h) {}22 23    double area() const override {24        return w_ * h_;25    }26 27    std::string name() const override {28        return "長方形";29    }30 31private:32    double w_;33    double h_;34};35 36class Circle : public Shape {37public:38    Circle(double r) : r_(r) {}39 40    double area() const override {41        return 3.14 * r_ * r_;42    }43 44    std::string name() const override {45        return "圓";46    }47 48private:49    double r_;50};51 52int main() {53    std::vector<std::unique_ptr<Shape>> shapes;54    shapes.push_back(std::make_unique<Rectangle>(3, 4));55    shapes.push_back(std::make_unique<Circle>(1));56    shapes.push_back(std::make_unique<Rectangle>(2, 5));57    double total = 0;58    for (const auto& s : shapes) {59        std::cout << s->name() << ":" << s->area() << '\n';60        total += s->area();61    }62    std::cout << "一共:" << total << '\n';63    return 0;64}
輸出
長方形:12
圓:3.14
長方形:10
一共:25.14

std::make_unique<Rectangle>(3, 4) 建一個 Rectangle,放進 vector 時成了 unique_ptr<Shape>,就像 Rectangle* 能變成 Shape* 一樣。迴圈只認識 Shape;明天加一個 Triangle 類,迴圈一個字都不用改。

shapes

shapes[0]unique_ptr<Shape>
shapes[1]unique_ptr<Shape>
shapes[2]unique_ptr<Shape>

堆

3 4Rectangle
1Circle
2 5Rectangle
shapes 裡每一格都是一個 unique_ptr<Shape>,指著堆上各不相同的物件;迴圈只管呼叫 s->area()

為什麼放指標,不用 std::vector<Shape>?Shape 元素只放得下一個 Shape,長方形放進去會被切成一個普通的形狀。類裡第一行的 virtual ~Shape() {} 在「虛解構函式」那一關講。

練習 2

加一個正方形

寫一個從 Shape 派生的類 Square:建構函式接收邊長,area 返回邊長乘邊長,name 返回 "正方形"。main 裡的迴圈不用改。程式要顯示下面幾行。

要顯示
長方形:6
正方形:16
正方形:1
一共:23
exercise2.cpp
1#include <iostream>2#include <memory>3#include <string>4#include <vector>5 6class Shape {7public:8    virtual ~Shape() {}9    virtual int area() const = 0;10    virtual std::string name() const = 0;11};12 13class Rectangle : public Shape {14public:15    Rectangle(int w, int h) : w_(w), h_(h) {}16 17    int area() const override {18        return w_ * h_;19    }20 21    std::string name() const override {22        return "長方形";23    }24 25private:26    int w_;27    int h_;28};29 30int main() {31    std::vector<std::unique_ptr<Shape>> shapes;32    shapes.push_back(std::make_unique<Rectangle>(2, 3));33    shapes.push_back(std::make_unique<Square>(4));34    shapes.push_back(std::make_unique<Square>(1));35    int total = 0;36    for (const auto& s : shapes) {37        std::cout << s->name() << ":" << s->area() << '\n';38        total += s->area();39    }40    std::cout << "一共:" << total << '\n';41    return 0;42}
輸出
點「執行」或按 Ctrl+Enter

純虛擬函式和抽象類

一個籠統的「形狀」面積是多少?沒有像樣的答案,放各種形狀的那個例子裡,Shape::area 的 return 0; 是湊的。不寫函式體,寫成 = 0,這個函式就是純虛擬函式:「每個派生類都必須自己寫」。有純虛擬函式的類叫抽象類:它就是用來當基類的,不能用它建物件。

main.cpp
1#include <iostream>2 3class Shape {4public:5    virtual ~Shape() {}6    virtual double area() const = 0;7};8 9class Square : public Shape {10public:11    Square(double side) : side_(side) {}12 13    double area() const override {14        return side_ * side_;15    }16 17private:18    double side_;19};20 21int main() {22    Square sq{3};23    std::cout << sq.area() << '\n';24    Shape s;25    return 0;26}
輸出
main.cpp: In function 'int main()':
main.cpp:24:11: error: cannot declare variable 's' to be of abstract type 'Shape'
   24 |     Shape s;
      |           ^
main.cpp:3:7: note:   because the following virtual functions are pure within 'Shape':
    3 | class Shape {
      |       ^~~~~
main.cpp:6:20: note:     'virtual double Shape::area() const'
    6 |     virtual double area() const = 0;
      |                    ^~~~

cannot declare variable 's' to be of abstract type 'Shape'。上一行的 Square sq{3}; 沒問題:它寫了 area。派生類忘了寫,它自己也還是抽象類,建它的物件會報同樣的錯,只是換成它的名字。這樣,新加一種形狀要寫哪些函式,編譯器一個個提醒你。抽象類的指標和引用沒問題,std::vector<std::unique_ptr<Shape>> 就是這樣放形狀的。

單選

Shape 有一個純虛擬函式 area。哪一句編譯不過?

虛解構函式

通過基類指標刪除一個派生類物件,執行的是誰的解構函式?沒有 virtual,還是老樣子:只有基類的。

main.cpp
1#include <iostream>2 3class Notification {4public:5    ~Notification() {6        std::cout << "通知清理完畢\n";7    }8 9    virtual void send() const = 0;10};11 12class Email : public Notification {13public:14    ~Email() {15        std::cout << "郵件草稿已刪除\n";16    }17 18    void send() const override {19        std::cout << "傳送一封郵件\n";20    }21};22 23int main() {24    Notification* n = new Email;25    n->send();26    delete n;27    return 0;28}
輸出
傳送一封郵件
通知清理完畢

「郵件草稿已刪除」一直沒出來:delete n 只知道 n 是 Notification*。要是 Email 有記憶體或檔案要還,就落下了。(按 C++ 的規定這是未定義行為,g++ 的做法就是你看到的這樣。用 g++ -Wall 編譯,它會在 delete n; 這一行警告:[-Wdelete-non-virtual-dtor]。)把基類的解構函式改成虛擬函式:

main.cpp
1#include <iostream>2 3class Notification {4public:5    virtual ~Notification() {6        std::cout << "通知清理完畢\n";7    }8 9    virtual void send() const = 0;10};11 12class Email : public Notification {13public:14    ~Email() {15        std::cout << "郵件草稿已刪除\n";16    }17 18    void send() const override {19        std::cout << "傳送一封郵件\n";20    }21};22 23int main() {24    Notification* n = new Email;25    n->send();26    delete n;27    return 0;28}
輸出
傳送一封郵件
郵件草稿已刪除
通知清理完畢

這回 delete n 找到了物件自己的解構函式 ~Email,它之後照常執行 ~Notification:先子後父,和上一課一樣。兩段程式都點單步,比一比 delete n; 之後程式去了哪裡。

~Notification()delete n;通知清理完畢漏掉了 ~Email
virtual ~Notification()delete n;郵件草稿已刪除 → 通知清理完畢先子後父
delete n(n 是 Notification*,指著一個 Email):解構函式不是虛的,只執行基類的;是虛的,先子後父都執行

std::unique_ptr<Notification> 和那個放形狀的 vector 也一樣:它們也是通過基類指標刪除的。規矩很短:有虛擬函式的類,解構函式也寫成虛的,哪怕是空的,像 virtual ~Shape() {}。

單選

什麼樣的類,解構函式要寫成虛的?

練習 3

修好它:沒刪掉的臨時檔案

每個 TempDownload 被刪除時應該刪掉自己的臨時檔案,可那幾行一直沒顯示。只改 Download 這個類(TempDownload 和 main 不動),讓輸出對上。

要顯示
下載 photo.jpg
下載 song.mp3
刪掉 song.mp3 的臨時檔案
關閉 song.mp3
刪掉 photo.jpg 的臨時檔案
關閉 photo.jpg
exercise3.cpp
1#include <iostream>2#include <memory>3#include <string>4 5class Download {6public:7    Download(const std::string& file) : file_(file) {}8 9    ~Download() {10        std::cout << "關閉 " << file_ << '\n';11    }12 13    virtual void start() const = 0;14 15protected:16    std::string file_;17};18 19class TempDownload : public Download {20public:21    TempDownload(const std::string& file) : Download(file) {}22 23    ~TempDownload() {24        std::cout << "刪掉 " << file_ << " 的臨時檔案\n";25    }26 27    void start() const override {28        std::cout << "下載 " << file_ << '\n';29    }30};31 32int main() {33    std::unique_ptr<Download> a = std::make_unique<TempDownload>("photo.jpg");34    std::unique_ptr<Download> b = std::make_unique<TempDownload>("song.mp3");35    a->start();36    b->start();37    return 0;38}
輸出
點「執行」或按 Ctrl+Enter

這一課學會了

  • 沒有 virtual 時,通過基類引用或指標呼叫的是基類的版本,編譯時就定死了。
  • 基類裡加上 virtual,呼叫時在程式執行時看物件,執行它那個類的版本:這叫多型。通過引用和指標才行,複製出來的不行。
  • 每個替換基類的函式都寫上 override:名字、引數、const 有一樣對不上,就得到 marked 'override', but does not override,而不是一個悄悄藏著的錯。
  • std::vector<std::unique_ptr<Shape>> 能放各種形狀,一個迴圈全管。
  • virtual double area() const = 0; 是純虛擬函式;有它的類是抽象類,不能建物件,派生類必須寫這個函式。
  • 有虛擬函式的類要有虛解構函式;沒有的話,通過基類指標刪除會漏掉派生類的解構函式。
第 24 課學完了嗎?第 24 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 25 課 · 20 分鐘模板一份程式碼給好幾種類型用:函式模板 template <typename T>,編譯器怎麼推出 T、推不出來的報錯,寫明型別,類別範本 Box<T> 和建在 vector 上的 Stack<T>。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。