C++ 類和物件
類(class)把資料(成員變數)和操作(成員函式)放在一起;private 成員只能在類裡面用,public 成員外面也能用。
第 14 課用 struct 把幾樣東西放在一起。它很方便,可也有個問題:誰都能直接改裡面的成員。一個銀行賬戶,餘額隨手就能改成負數:
1#include <iostream>2#include <string>3 4struct Account {5 std::string owner;6 int balance;7};8 9int main() {10 Account acc{"小林", 100};11 acc.balance = -5000;12 std::cout << acc.owner << " 的餘額:" << acc.balance << '\n';13 return 0;14}
小林 的餘額:-5000
編譯器不攔著,程式也照常跑完。這一課講 class:把資料藏起來,只讓外面通過幾個函式用它,規矩由這個型別自己守著。
用 struct 時,main 裡直接把餘額改成 -5000,會怎樣?
struct 的成員誰都能改,編譯器不會攔著。這正是這一課要解決的問題:讓型別自己守住規矩。成員函式
struct 和 class 裡不光能放變數,還能放函式。寫在裡面的函式叫成員函式,它直接用得到同一個物件的成員變數:
1#include <iostream>2 3struct Counter {4 int count = 0;5 6 void add() {7 count++;8 }9 10 void show() {11 std::cout << "現在是 " << count << '\n';12 }13};14 15int main() {16 Counter people;17 Counter cars;18 people.add();19 people.add();20 cars.add();21 people.show();22 cars.show();23 return 0;24}
現在是 2 現在是 1
int count = 0; 給成員一個起始值。Counter 是型別,people 和 cars 是這個型別的兩個物件,各有各的 count。呼叫成員函式也用 .:people.add() 加的是 people 的 count,和 cars 沒關係。點單步,看畫面上兩個物件各自的欄位怎麼變。
count
add()show()
people: Counter- count = 2
cars: Counter- count = 1
這段程式顯示什麼?
1#include <iostream>2 3struct Box {4 int n = 0;5 6 void add(int k) {7 n += k;8 }9};10 11int main() {12 Box a;13 Box b;14 a.add(2);15 b.add(5);16 a.add(1);17 std::cout << a.n << ' ' << b.n << '\n';18 return 0;19}
a 和 b 各有自己的 n。a 加了 2 又加了 1,是 3;b 只加了 5。class 和 private
把 struct 換成 class,再用 public: 和 private: 分開:public: 下面的誰都能用,private: 下面的只有這個類自己的成員函式能用。
1#include <iostream>2 3class Account {4public:5 void deposit(int amount) {6 if (amount > 0) {7 balance_ += amount;8 }9 }10 11 int balance() {12 return balance_;13 }14 15private:16 int balance_ = 0;17};18 19int main() {20 Account acc;21 acc.deposit(300);22 acc.deposit(-50);23 std::cout << "餘額:" << acc.balance() << '\n';24 return 0;25}
餘額:300
餘額 balance_ 是私有的,外面只能通過 deposit 存錢,deposit 又不收負數,所以 -50 沒存進去。這門課給私有的成員變數名後面加一個下劃線(balance_),一眼就能看出哪些是成員;讀餘額的函式就可以叫 balance(),不會撞名。
class Account {public: void deposit①(int amount); int balance();private: int balance_② = 0;};
- ①外面只能通過它們讀寫餘額
- ②名字加下劃線:一看就是私有成員
外面硬要直接改,就是編譯錯誤:
1#include <iostream>2 3class Account {4public:5 int balance() {6 return balance_;7 }8 9private:10 int balance_ = 0;11};12 13int main() {14 Account acc;15 acc.balance_ = -5000;16 std::cout << acc.balance() << '\n';17 return 0;18}
main.cpp: In function 'int main()':
main.cpp:15:9: error: 'int Account::balance_' is private within this context
15 | acc.balance_ = -5000;
| ^~~~~~~~
main.cpp:10:9: note: declared private here
10 | int balance_ = 0;
| ^~~~~~~~先看第一個 error::'int Account::balance_' is private within this context,balance_ 是私有的,在這裡用不了。g++ 接著還會用 note: 指出它是在哪一行宣告的。
private: 下面的成員變數,誰能直接用?
main 連讀都不行:直接寫 acc.balance_ 就是編譯錯誤。為什麼要 private
把資料藏起來,不是為了讓人用著麻煩,而是讓規矩只寫在一個地方。賬戶的規矩是「餘額不能變成負數」,那麼取錢的檢查就寫在 withdraw 裡,外面誰也繞不過去:
1#include <iostream>2 3class Account {4public:5 void deposit(int amount) {6 if (amount > 0) {7 balance_ += amount;8 }9 }10 11 bool withdraw(int amount) {12 if (amount <= 0 || amount > balance_) {13 return false;14 }15 balance_ -= amount;16 return true;17 }18 19 int balance() {20 return balance_;21 }22 23private:24 int balance_ = 0;25};26 27int main() {28 Account acc;29 acc.deposit(100);30 std::cout << acc.withdraw(30) << '\n';31 std::cout << acc.withdraw(500) << '\n';32 std::cout << "餘額:" << acc.balance() << '\n';33 return 0;34}
1 0 餘額:70
取 30 成功(顯示 1),取 500 不夠(顯示 0),餘額還是 70。以後哪裡出了負數,只要查這個類就行。
還有一個好處:外面只認得 deposit、withdraw、balance 這幾個函式。哪天想把餘額改成按「分」存,或者加一條流水記錄,只改類裡面,用它的程式碼一行都不用動。
這段程式顯示什麼?
1#include <iostream>2 3class Light {4public:5 void toggle() {6 on_ = !on_;7 if (on_) {8 times_++;9 }10 }11 12 int times() {13 return times_;14 }15 16private:17 bool on_ = false;18 int times_ = 0;19};20 21int main() {22 Light lamp;23 lamp.toggle();24 lamp.toggle();25 lamp.toggle();26 std::cout << lamp.times() << '\n';27 return 0;28}
times_ 只在開啟時加 1。燈從關開始:第一次開啟(1),第二次關上,第三次又開啟(2)。計步器
✓寫完 StepCounter:add(steps) 把步數加上去,但負數不算;total() 返回一共走了多少步。程式要顯示 今天走了 9000 步。
今天走了 9000 步
1#include <iostream>2 3class StepCounter {4public:5 6private:7 int total_ = 0;8};9 10int main() {11 StepCounter today;12 today.add(3500);13 today.add(-200);14 today.add(5500);15 std::cout << "今天走了 " << today.total() << " 步\n";16 return 0;17}
const 成員函式
第 10 課說過,大的東西只看不改時傳 const 引用。可是把 Account 用 const Account& 傳進函式,呼叫 balance() 卻編譯不過:
1#include <iostream>2 3class Account {4public:5 int balance() {6 return balance_;7 }8 9private:10 int balance_ = 70;11};12 13void report(const Account& acc) {14 std::cout << "餘額:" << acc.balance() << '\n';15}16 17int main() {18 Account acc;19 report(acc);20 return 0;21}
main.cpp: In function 'void report(const Account&)':
main.cpp:14:41: error: passing 'const Account' as 'this' argument discards qualifiers [-fpermissive]
14 | std::cout << "餘額:" << acc.balance() << '\n';
| ~~~~~~~~~~~^~報錯說 passing 'const Account' as 'this' argument discards qualifiers:acc 是 const 的,可 balance() 沒有保證自己不改物件,編譯器不敢呼叫它。(this 是指向物件自己的指標,第 19 課講指標時再說。)
辦法是在只看不改的成員函式的括號後面加 const:
1#include <iostream>2 3class Account {4public:5 int balance() const {6 return balance_;7 }8 9private:10 int balance_ = 70;11};12 13void report(const Account& acc) {14 std::cout << "餘額:" << acc.balance() << '\n';15}16 17int main() {18 Account acc;19 report(acc);20 return 0;21}
餘額:70
int balance() const 說的是:這個函式不改物件。要是在裡面改了 balance_,就是編譯錯誤。只看不改的成員函式(讀數、顯示、計算)都加上 const,養成習慣。
show 拿到的是 const Square&。選一個詞填進空格,讓程式編譯通過並顯示 16。
1#include <iostream>2 3class Square {4public:5 int area() {6 return side_ * side_;7 }8 9private:10 int side_ = 4;11};12 13void show(const Square& s) {14 std::cout << s.area() << '\n';15}16 17int main() {18 Square sq;19 show(sq);20 return 0;21}
const 物件只能呼叫 const 成員函式。int area() const 保證不改物件,show 才能呼叫它。修好它:只看不改要加 const
✓程式編譯不過。只改 Account 類,讓它顯示 餘額:250。
餘額:250
1#include <iostream>2 3class Account {4public:5 void deposit(int amount) {6 balance_ += amount;7 }8 9 int balance() {10 return balance_;11 }12 13private:14 int balance_ = 0;15};16 17void report(const Account& acc) {18 std::cout << "餘額:" << acc.balance() << '\n';19}20 21int main() {22 Account acc;23 acc.deposit(250);24 report(acc);25 return 0;26}
一個溫度類
再看一個完整的例子。溫度不能低於絕對零度 −273.15 °C,set_celsius 守著這條規矩;華氏度不存,要的時候現算:
1#include <iostream>2 3class Temperature {4public:5 bool set_celsius(double c) {6 if (c < -273.15) {7 return false;8 }9 celsius_ = c;10 return true;11 }12 13 double celsius() const {14 return celsius_;15 }16 17 double fahrenheit() const {18 return celsius_ * 9 / 5 + 32;19 }20 21private:22 double celsius_ = 0;23};24 25int main() {26 Temperature t;27 t.set_celsius(25);28 t.set_celsius(-300);29 std::cout << t.celsius() << " °C = " << t.fahrenheit() << " °F\n";30 return 0;31}
25 °C = 77 °F
-300 被拒絕了,溫度還是 25 度。現在每個物件一開始都是 0 度,要另外呼叫 set_celsius 才有值;下一課的建構函式讓物件一出生就帶上該有的值。
這段程式顯示什麼?
1#include <iostream>2 3class Temperature {4public:5 bool set_celsius(double c) {6 if (c < -273.15) {7 return false;8 }9 celsius_ = c;10 return true;11 }12 13 double fahrenheit() const {14 return celsius_ * 9 / 5 + 32;15 }16 17private:18 double celsius_ = 0;19};20 21int main() {22 Temperature t;23 t.set_celsius(100);24 t.set_celsius(-500);25 std::cout << t.fahrenheit() << '\n';26 return 0;27}
set_celsius(100) 成功;-500 低於絕對零度,被拒絕,溫度還是 100。100 × 9 / 5 + 32 = 212。歌單有多長
✓Playlist 用 vector 存每首歌的秒數。給它加一個 const 成員函式 total_minutes(),返回一共多少分鐘(整數除法,不足一分鐘的不算)。程式要顯示 3 首,11 分鐘。
3 首,11 分鐘
1#include <iostream>2#include <vector>3 4class Playlist {5public:6 void add(int seconds) {7 songs_.push_back(seconds);8 }9 10 int count() const {11 return songs_.size();12 }13 14private:15 std::vector<int> songs_;16};17 18int main() {19 Playlist p;20 p.add(215);21 p.add(250);22 p.add(240);23 std::cout << p.count() << " 首," << p.total_minutes() << " 分鐘\n";24 return 0;25}
struct 和 class 的區別
在 C++ 裡,struct 和 class 幾乎一樣,struct 也能有成員函式、private:。只差一點:沒寫 public: 或 private: 時,struct 的成員預設是公開的,class 的預設是私有的。
struct P { int x = 3; }; p.x3沒寫的預設 publicclass P { int x = 3; }; p.x編譯錯誤沒寫的預設 private這段程式會怎樣?
1#include <iostream>2 3class Point {4 int x = 3;5};6 7int main() {8 Point p;9 std::cout << p.x << '\n';10 return 0;11}
class 裡沒寫 public: 的成員預設是私有的,main 裡用 p.x 就是編譯錯誤:'int Point::x' is private within this context。換成 struct 就能顯示 3。習慣上:只是把幾樣資料放在一起、沒什麼規矩要守的,用 struct(像第 14 課的 Item);有規矩要守、資料要藏起來的,用 class,先寫 public: 部分,再寫 private: 部分。
這一課學會了
- 寫在
struct/class裡的函式是成員函式,用物件.函式()呼叫,直接用得到這個物件的成員變數;每個物件有自己的一份成員變數。 public:下面的誰都能用,private:下面的只有類自己的成員函式能用;外面用了私有成員是編譯錯誤(is private within this context)。- 把資料設成
private,改它只能通過成員函式,規矩(餘額不為負、溫度不低於絕對零度)就只寫在一個地方。 - 只看不改的成員函式在括號後面加
const;const物件和const引用只能呼叫這樣的函式。 struct和class只差預設的訪問許可權:struct預設公開,class預設私有。- 這門課給私有成員變數名加下劃線:
balance_。