📌 就像是設計圖
設計娃娃會有什麼名字、年齡
用來描述一種東西
應該有的屬性和方法
📌 就像是保險箱
把變數和函式包在一起
保護資料,不能隨便修改
public
任何人都能使用
private
只有自己能使用
#include <iostream>
using namespace std;
class Student
{
private:
string name;
int age;
public:
void Data(string n, int a)
{
this -> name = n;
this -> age = a;
}
void OutPut()
{
cout << "姓名: " << name << endl;
cout << "年齡: " << age << endl;
}
};
int main()
{
Student s;
s.Data("小赤", 16);
s.OutPut();
return 0;
}
📌 this 指向變數(指標)
作用 | |
---|---|
private |
只有在類別內部可存取,外部不可直接使用 |
public |
可以讓外部程式自由存取或呼叫 |
📌 資料和功能整合成一個大藍圖
透過封裝來保護內部資料
允許外部透過公開函式進行操作
避免直接修改造成錯誤
private
→ 提供保護
public
→ 提供不同的方法