博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
十五、类与封装的概念
阅读量:7223 次
发布时间:2019-06-29

本文共 2087 字,大约阅读时间需要 6 分钟。

1、类的封装

C++中类的封装:

  • 成员变量:C++中用于表示类属性的变量
  • 成员函数:C++中用于表示类行为的函数
  • C++中可以给成员变量和成员函数定义访问级别

    • public:成员变量和成员函数可以在类的內部和外界访问和调用
    • private:成员变量和成员函数只能在类的内部被访问和调用
#include 
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;}

2、类成员的作用域

类成员的作用域:

  • 类成员的作用域都只在类的内部,外部无法直接访问
  • 成员函数可以直接访问成员变量和调用成员函数
  • 类的外部可以通过类变量访问public成员
  • 类成员的作用域与访问级别没有关系

C++中用struct定义的夫中所有成员默认为 public

#include 
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;}

3、小结

类通常可以分为使用方式和内部细节两部分

类的封裝机制使得使用方式和内部细节相分离

C++中通过定义类成员的访问级别实现封装机制

public成员可以在类的内部和外界访问和调用

private成员只能在类的内部被访问和调用

转载地址:http://yjkfm.baihongyu.com/

你可能感兴趣的文章
oracle授权动态视图权限给用户
查看>>
Debian – 出现-bash: pip: command not found错误解决办法
查看>>
Zxing扫描二维码
查看>>
我的友情链接
查看>>
aspcms后台拿shell漏洞(非添加模块)及修复方法
查看>>
C语言冒泡排序法
查看>>
B2B行业门户网站群发邮件时间及发送频率
查看>>
关于虚拟机能ping通物理机,而物理机ping不通虚拟机问题解决。
查看>>
同台机器启动多个mysql
查看>>
iframe 跨域高度自适应
查看>>
struts2+hibernate3+spring3(ssh2)框架下的web应用
查看>>
Linux下的三个时间属性
查看>>
semanage
查看>>
[case分享]Exchange 2010 登陆OWA查看邮件出现Rights managem operation failed
查看>>
linux dd 读取 写入磁盘速度
查看>>
dmidecode查看linux硬件信息
查看>>
linux监控对象及重要性
查看>>
walle-web自动化部署配置
查看>>
opencv轮廓提取、轮廓识别相关要点
查看>>
BOOST.ASIO源码剖析(一)
查看>>