1、類的封裝
C++中類的封裝:
- 成員變量:C++中用于表示類屬性的變量
- 成員函數:C++中用于表示類行為的函數
-
C++中可以給成員變量和成員函數定義訪問級別
-
public
:成員變量和成員函數可以在類的內部和外界訪問和調用 -
private
:成員變量和成員函數只能在類的內部被訪問和調用
-
#include <stdio.h>struct Biology
{bool living;
};struct Animal : Biology
{bool movable;void findFood(){ }
};struct Plant : Biology
{bool growable;
};struct Beast : Animal
{void sleep() { }
};struct Human : Animal
{void sleep() { printf("I'm sleeping...\n");}void work() { printf("I'm working...\n");}
};struct Girl : Human
{
private:int age;int weight;
// private修飾兩個屬性,定義訪問級別為私有public:void print(){age = 22;weight = 48;printf("I'm a girl, I'm %d years old.\n", age);printf("My weight is %d kg.\n", weight);}
};struct Boy : Human
{
private:int height;int salary;
public:int age;int weight;void print(){height = 175;salary = 9000;printf("I'm a boy, my height is %d cm.\n", height);printf("My salary is %d RMB.\n", salary);}
};int main()
{Girl g;Boy b;g.age = 20; // 編譯不過g.print(); // 通過print()去訪問b.age = 19; // okb.weight = 120;b.height = 180; // errb.print();return 0;
}
2、類成員的作用域
類成員的作用域:
- 類成員的作用域都只在類的內部,外部無法直接訪問
- 成員函數可以直接訪問成員變量和調用成員函數
- 類的外部可以通過類變量訪問
public
成員 - 類成員的作用域與訪問級別沒有關系
C++中用struct
定義的夫中所有成員默認為 public
#include <stdio.h>int i = 1;struct Test
{
private:int i;public:int j;int getI(){i = 3;return i;}
};int main()
{int i = 2;Test test;test.j = 4;printf("i = %d\n", i); // i = 2;printf("::i = %d\n", ::i); // ::i = 1; 訪問默認命名空間,即全局作用域// printf("test.i = %d\n", test.i); // Error, test.i是私有的printf("test.j = %d\n", test.j); // test.j = 4printf("test.getI() = %d\n", test.getI()); // test.getI() = 3return 0;
}
3、小結
類通常可以分為使用方式和內部細節兩部分類的封裝機制使得使用方式和內部細節相分離
C++中通過定義類成員的訪問級別實現封裝機制
public成員可以在類的內部和外界訪問和調用
private成員只能在類的內部被訪問和調用