10-2 存取控制——public 與 private
一、class 裡的東西,不是誰都可以動的
先看一個銀行帳戶的例子。
#include <iostream>
using namespace std;
class BankAccount {
public:
string owner;
int balance;
};
int main() {
BankAccount acc;
acc.owner = "小明";
acc.balance = 1000;
acc.balance = -99999; // 沒有任何阻擋,帳戶餘額變成負的!
cout << acc.balance << endl;
}
這是因為我們之前在 class 裡用了 public 這個存取修飾詞。 public 的意思就是「公開的」,誰想看、誰想改都可以。
用 private 將存取限制改為「私有的」看看差別。
#include <iostream>
using namespace std;
class BankAccount {
private:
string owner;
int balance;
};
int main() {
BankAccount acc;
acc.owner = "小明";
acc.balance = 1000;
acc.balance = -99999; // 沒有任何阻擋,帳戶餘額變成負的!
cout << acc.balance << endl;
}
修改之後,連編譯都失敗了,出現了大量如下的錯誤訊息。
main.cpp:13:9: error: 'std::string BankAccount::owner' is private within this context
13 | acc.owner = "小明";
| ^~~~~
main.cpp:7:12: note: declared private here
7 | string owner;
| ^~~~~
main.cpp:14:9: error: 'int BankAccount::balance' is private within this context
14 | acc.balance = 1000;
| ^~~~~~~
main.cpp:8:9: note: declared private here
8 | int balance;
| ^~~~~~~
main.cpp:16:9: error: 'int BankAccount::balance' is private within this context
16 | acc.balance = -99999; // 沒有任何阻擋,帳戶餘額變成負的!
| ^~~~~~~
main.cpp:8:9: note: declared private here
8 | int balance;
| ^~~~~~~
main.cpp:18:17: error: 'int BankAccount::balance' is private within this context
18 | cout << acc.balance << endl;
| ^~~~~~~
main.cpp:8:9: note: declared private here
8 | int balance;
| ^~~~~~~