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; // ok b.weight = 120; b.height = 180; // err b.print(); return 0; }
类成员的做用域:code
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 = 4 printf("test.getI() = %d\n", test.getI()); // test.getI() = 3 return 0; }
类一般能够分为使用方式和内部细节两部分类的封裝机制使得使用方式和内部细节相分离get
C++中经过定义类成员的访问级别实现封装机制io
public成员能够在类的内部和外界访问和调用编译
private成员只能在类的内部被访问和调用ast