Kodewick
開始學 →
繼承23 / 30

C++ 繼承

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

繼承讓派生類自動擁有基類的成員,寫成 class Dog : public Animal;建立物件時先構造基類,銷燬時先析構派生類。

活期賬戶和儲蓄賬戶都有餘額、都能存錢;儲蓄賬戶另外還能算利息。寫成兩個各管各的類,餘額和 deposit 就要寫兩遍,一份裡修好的錯,另一份裡還在。繼承讓一樣的部分只寫一次,寫在一個類裡,另一個類在它上面接著蓋:

main.cpp
1#include <iostream>2 3class Account {4public:5    void deposit(int amount) {6        balance_ += amount;7    }8 9    int balance() const {10        return balance_;11    }12 13private:14    int balance_ = 0;15};16 17class SavingsAccount : public Account {18public:19    void add_interest(int percent) {20        deposit(balance() * percent / 100);21    }22};23 24int main() {25    SavingsAccount s;26    s.deposit(200);27    s.add_interest(5);28    std::cout << "餘額:" << s.balance() << '\n';29    return 0;30}
輸出
餘額:210

SavingsAccount 裡沒有寫 deposit、balance、balance_,s.deposit(200) 卻能用:這些都是從 Account 那裡繼承來的。它只寫了自己新加的 add_interest。點單步:s 裡面先是一塊 <Account>,balance_ 就在裡面,存錢時變的是這一塊。

Account
  • −balance_
  • +deposit()
  • +balance()
SavingsAccount
  • +add_interest()
SavingsAccount 是一種 Account:balance_、deposit() 和 balance() 都繼承過來了,它自己只寫了 add_interest()

基類和派生類

class SavingsAccount : public Account 讀作「SavingsAccount 是一種 Account,再加上這裡寫的」。Account 叫基類(也叫父類),SavingsAccount 叫派生類(也叫子類)。一個基類可以有好幾個派生類:活期賬戶、儲蓄賬戶、兒童賬戶都可以建在 Account 上。

派生類拿到了基類的所有成員,可基類的 private 成員還是基類自己的:派生類的成員函式也碰不到。試試把利息直接加到 balance_ 上:

main.cpp
1#include <iostream>2 3class Account {4public:5    void deposit(int amount) {6        balance_ += amount;7    }8 9    int balance() const {10        return balance_;11    }12 13private:14    int balance_ = 0;15};16 17class SavingsAccount : public Account {18public:19    void add_interest(int percent) {20        balance_ += balance_ * percent / 100;21    }22};23 24int main() {25    SavingsAccount s;26    s.deposit(200);27    s.add_interest(5);28    std::cout << "餘額:" << s.balance() << '\n';29    return 0;30}
輸出
main.cpp: In member function 'void SavingsAccount::add_interest(int)':
main.cpp:20:9: error: 'int Account::balance_' is private within this context
   20 |         balance_ += balance_ * percent / 100;
      |         ^~~~~~~~
main.cpp:14:9: note: declared private here
   14 |     int balance_ = 0;
      |         ^~~~~~~~

'int Account::balance_' is private within this context。private 的意思是隻有 Account 自己的成員函式能用,派生類也不行。所以第一個例子繞了一下,用的是 public 的 deposit 和 balance。

注意: : public Account 裡的 public 一定要寫。不寫的話,class 是按 private 方式繼承,那是另一回事(這門課不用)。

單選

class Cat : public Animal 裡,哪個是基類?

protected

public 和 private 中間還有一級:protected。類自己的函式和派生類的函式都能用,外面的程式碼還是不能用。

main.cpp
1#include <iostream>2 3class Account {4public:5    void deposit(int amount) {6        balance_ += amount;7    }8 9    int balance() const {10        return balance_;11    }12 13protected:14    int balance_ = 0;15};16 17class SavingsAccount : public Account {18public:19    void add_interest(int percent) {20        balance_ += balance_ * percent / 100;21    }22};23 24int main() {25    SavingsAccount s;26    s.deposit(200);27    s.add_interest(5);28    s.balance_ = 1000000;29    std::cout << "餘額:" << s.balance() << '\n';30    return 0;31}
輸出
main.cpp: In function 'int main()':
main.cpp:28:7: error: 'int Account::balance_' is protected within this context
   28 |     s.balance_ = 1000000;
      |       ^~~~~~~~
main.cpp:14:9: note: declared protected here
   14 |     int balance_ = 0;
      |         ^~~~~~~~

這回 add_interest 編譯通過了。錯在第 28 行,在 main 裡:'int Account::balance_' is protected within this context。對 main 來說,protected 和 private 一樣。刪掉這一行,就顯示「餘額:210」。

小技巧: protected 的資料,以後誰寫的派生類都能改,沒有 private 安全。像第一個例子那樣用 public 成員函式就夠的時候,資料還是放 private;派生類真正需要的才放 protected。

多選可以選多個

基類裡 protected 的成員,哪些地方能用?(可以選好幾個)

練習 1

修好它:加速碰不到速度

SportsCar::boost 編譯不過。改 Vehicle 裡的一個詞,讓派生類能改 speed_,而 speed_ 對類外面還是藏著的(main 不能改它,所以不能改成 public)。程式要顯示 130 180。

要顯示
130 180
exercise1.cpp
1#include <iostream>2 3class Vehicle {4public:5    Vehicle(int speed) : speed_(speed) {}6 7    int speed() const {8        return speed_;9    }10 11private:12    int speed_;13};14 15class SportsCar : public Vehicle {16public:17    SportsCar(int speed) : Vehicle(speed) {}18 19    void boost() {20        speed_ += 30;21    }22};23 24int main() {25    SportsCar a{100};26    SportsCar b{120};27    a.boost();28    b.boost();29    b.boost();30    std::cout << a.speed() << " " << b.speed() << '\n';31    return 0;32}
輸出
點「執行」或按 Ctrl+Enter

構造:先父後子

派生類的物件裡面有一塊基類的部分,這一塊由基類的建構函式來建。派生類的建構函式在初始化列表裡用基類的名字呼叫它:: Animal(name)。讓每個建構函式和解構函式都顯示一行,就能看出先後:

main.cpp
1#include <iostream>2#include <string>3 4class Animal {5public:6    Animal(const std::string& name) : name_(name) {7        std::cout << "動物 " << name_ << " 建好了\n";8    }9 10    ~Animal() {11        std::cout << "動物 " << name_ << " 拆掉了\n";12    }13 14protected:15    std::string name_;16};17 18class Dog : public Animal {19public:20    Dog(const std::string& name, const std::string& breed) : Animal(name), breed_(breed) {21        std::cout << "狗 " << name_ << "(" << breed_ << ")建好了\n";22    }23 24    ~Dog() {25        std::cout << "狗 " << name_ << " 拆掉了\n";26    }27 28private:29    std::string breed_;30};31 32int main() {33    Dog d{"旺財", "比格犬"};34    std::cout << "--- main 結束\n";35    return 0;36}
輸出
動物 旺財 建好了
狗 旺財(比格犬)建好了
--- main 結束
狗 旺財 拆掉了
動物 旺財 拆掉了

建的時候先父後子:先建 Animal 那一塊,再建 Dog 自己的成員,最後執行 Dog 建構函式的函式體,這時用 name_ 已經沒問題了。拆的時候反過來:先 Dog 的解構函式,再 Animal 的。像蓋房子:先打地基,最後上屋頂;拆的時候先拆屋頂。在第 33 行點單步,看程式進了 Dog 的建構函式,又跳到 Animal 的,再回來。

① 先建基類那一塊Animal(name)
② 再建 Dog 的成員breed_(breed)
Dog 的函式體③ 最後
④ 拆:先子~Dog()
⑤ 後父~Animal()
建的時候先父後子,拆的時候反過來:先子後父

如果初始化列表裡沒寫 Animal(name),編譯器就用 Animal() 來建基類部分,這裡沒有這個建構函式,於是報錯 no matching function for call to 'Animal::Animal()'。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2 3class Vehicle {4public:5    Vehicle() {6        std::cout << "V+ ";7    }8 9    ~Vehicle() {10        std::cout << "V- ";11    }12};13 14class Car : public Vehicle {15public:16    Car() {17        std::cout << "C+ ";18    }19 20    ~Car() {21        std::cout << "C- ";22    }23};24 25int main() {26    Car c;27    return 0;28}
練習 2

入住和退房

給 Suite 寫一個建構函式,接收房間號,顯示 套房 101:迷你吧裝滿;再寫一個解構函式,顯示 套房 101:迷你吧清空(號碼是它自己的)。Room 已經會顯示自己的那幾行。輸出要一模一樣。

要顯示
房間 101 準備好了
套房 101:迷你吧裝滿
房間 102 準備好了
套房 102:迷你吧裝滿
熄燈
套房 102:迷你吧清空
房間 102 打掃好了
套房 101:迷你吧清空
房間 101 打掃好了
exercise2.cpp
1#include <iostream>2 3class Room {4public:5    Room(int number) : number_(number) {6        std::cout << "房間 " << number_ << " 準備好了\n";7    }8 9    ~Room() {10        std::cout << "房間 " << number_ << " 打掃好了\n";11    }12 13protected:14    int number_;15};16 17class Suite : public Room {18public:19};20 21int main() {22    Suite a{101};23    Suite b{102};24    std::cout << "熄燈\n";25    return 0;26}
輸出
點「執行」或按 Ctrl+Enter

派生類改寫基類的函式

派生類可以寫一個和基類裡同名的函式。經理的介紹和普通員工一樣,再加上帶幾個人:

main.cpp
1#include <iostream>2#include <string>3 4class Employee {5public:6    Employee(const std::string& name, int salary) : name_(name), salary_(salary) {}7 8    void describe() const {9        std::cout << name_ << ",月薪 " << salary_ << '\n';10    }11 12protected:13    std::string name_;14    int salary_;15};16 17class Manager : public Employee {18public:19    Manager(const std::string& name, int salary, int team) : Employee(name, salary), team_(team) {}20 21    void describe() const {22        Employee::describe();23        std::cout << "  帶 " << team_ << " 個人\n";24    }25 26private:27    int team_;28};29 30int main() {31    Employee e{"小林", 4000};32    Manager m{"老王", 6000, 5};33    e.describe();34    m.describe();35    return 0;36}
輸出
小林,月薪 4000
老王,月薪 6000
  帶 5 個人

m.describe() 找到的是 Manager 的 describe,它把 Employee 裡的那個隱藏了。在它裡面,Employee::describe() 寫全名呼叫基類的版本,第一行就不用再寫一遍。如果漏了 Employee::,describe() 呼叫的是 Manager 的版本,也就是自己,一遍又一遍,停不下來。

單選

在 Manager::describe 裡,想先執行基類的版本,再加一行。怎麼呼叫基類的版本?

練習 3

書也是商品

寫一個從 Product 派生的類 Book。它多一個作者;建構函式接收書名、價格和作者,它的 show 先顯示商品那一行,再單獨一行顯示 作者: 和作者名。程式要顯示下面四行。

要顯示
三體:23 元
  作者:劉慈欣
活著:20 元
  作者:餘華
exercise3.cpp
1#include <iostream>2#include <string>3 4class Product {5public:6    Product(const std::string& name, int price) : name_(name), price_(price) {}7 8    void show() const {9        std::cout << name_ << ":" << price_ << " 元\n";10    }11 12private:13    std::string name_;14    int price_;15};16 17// 在這裡寫 Book 類18 19int main() {20    Book a{"三體", 23, "劉慈欣"};21    Book b{"活著", 20, "餘華"};22    a.show();23    b.show();24    return 0;25}
輸出
點「執行」或按 Ctrl+Enter

派生類物件能當基類用

經理也是員工,所以要員工的地方,都能放經理。引數是 const Employee& 的函式,兩種都能用:

main.cpp
1#include <iostream>2#include <string>3 4class Employee {5public:6    Employee(const std::string& name, int salary) : name_(name), salary_(salary) {}7 8    const std::string& name() const {9        return name_;10    }11 12protected:13    std::string name_;14    int salary_;15};16 17class Manager : public Employee {18public:19    Manager(const std::string& name, int salary, int team) : Employee(name, salary), team_(team) {}20 21private:22    int team_;23};24 25void show_badge(const Employee& e) {26    std::cout << "[ " << e.name() << " ]\n";27}28 29int main() {30    Employee e{"小林", 4000};31    Manager m{"老王", 6000, 5};32    show_badge(e);33    show_badge(m);34    Employee* p = &m;35    std::cout << p->name() << '\n';36    return 0;37}
輸出
[ 小林 ]
[ 老王 ]
老王

一個 show_badge 管所有員工:引用 e 只看見 m 裡 Employee 的那一塊。指標也一樣:Employee* p = &m;。反過來不行:不是每個員工都是經理,所以 Manager* q = &e; 是編譯錯誤。

只看見 Employee 那一塊,有一個問題:

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <string>3 4class Employee {5public:6    void describe() const {7        std::cout << "員工\n";8    }9};10 11class Manager : public Employee {12public:13    void describe() const {14        std::cout << "經理\n";15    }16};17 18int main() {19    Manager m;20    Employee* p = &m;21    p->describe();22    return 0;23}
單選

有 Employee e{...}; 和 Manager m{...};,哪一句編譯不過?

複製成基類物件

基類的指標或引用,連著的還是整個物件。複製成一個基類物件就不一樣了:Employee 型別的變數只放得下 Employee 那一塊,多出來的部分被切掉。這叫切片(slicing):

main.cpp
1#include <iostream>2#include <string>3 4class Employee {5public:6    Employee(const std::string& name, int salary) : name_(name), salary_(salary) {}7 8    void describe() const {9        std::cout << name_ << ",月薪 " << salary_ << '\n';10    }11 12protected:13    std::string name_;14    int salary_;15};16 17class Manager : public Employee {18public:19    Manager(const std::string& name, int salary, int team) : Employee(name, salary), team_(team) {}20 21private:22    int team_;23};24 25int main() {26    Manager m{"老王", 6000, 5};27    Employee copy = m;28    copy.describe();29    return 0;30}
輸出
老王,月薪 6000

copy 是一個普通的 Employee,有老王的名字和月薪,team_ 沒有跟過來。點單步:m 裡有一塊 <Employee> 和 team_,copy 裡只有名字和月薪。要把派生類物件當基類用,傳引用或指標,不要複製。

堆疊

mManager"老王" 6000 5
copyEmployee"老王" 6000

copy 是一個 Employee:只放得下名字和月薪,m 的 team_ 被切掉了
單選

Employee copy = m;(m 是一個 Manager)之後,copy 裡有什麼?

這一課學會了

  • class Derived : public Base 在一個類上面接著蓋另一個類:派生類拿到基類的成員,再加上自己的。public 一定要寫。
  • 基類的 private 成員,派生類裡也不能用;protected 成員派生類能用,外面不能用。
  • 派生類的建構函式在初始化列表裡建基類部分:: Animal(name)。建的時候先父後子;析構反過來,先子後父。
  • 派生類裡同名的函式會隱藏基類的;Base::f() 呼叫基類的版本。
  • 派生類物件可以當 Base& 傳、用 Base* 指著。通過它們呼叫的是基類的函式,即使派生類改寫了;第 24 課解決這個問題。
  • 把派生類物件複製成基類物件,只留下基類那一塊(切片)。
第 23 課學完了嗎?第 23 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 24 課 · 25 分鐘虛擬函式和多型讓基類指標調到對的版本:virtual 和 override、一個 vector 裡放各種形狀、純虛擬函式和抽象類、虛解構函式。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。