C++ 中封装的含义和简单实现

您所在的位置:网站首页 封装如何实现连续加工 C++ 中封装的含义和简单实现

C++ 中封装的含义和简单实现

2024-07-16 03:51| 来源: 网络整理| 查看: 265

其实封装并不是编程中的一个思想,对于很多领域来说都是这样。对于电子器件来说,我们不关心其内部的结构,只在乎该器件能够实现什么样的功能。这样对于顾客来说,不用花时间研究内部的实现过程,而对于商家来说,也可以更好的保护它们的商业秘密。

而对于 C++ 来说也是这样,借由数据类型也可以实现封装。这样做的好处就是对外屏蔽了功能实现,对内开放了数据权限。

C++ 中的类和对象是经由 C 中的 struct 发展而来的,就好像 struct 是由数组发展而来的一样。因此我们可以先通过 struct 实现封装。

封装实现 #include using std::cout; using std::endl; typedef struct complex { int x; int y; }COMP; void init(COMP &tmp,int x,int y) { tmp.x = x; tmp.y = y; } COMP * operator +(COMP &tmp1,COMP &tmp2) { COMP *p = static_cast(new COMP); p->x = tmp1.x + tmp2.x; p->y = tmp1.y + tmp2.y; return p; } COMP * operator -(COMP &tmp1,COMP &tmp2) { COMP *p = static_cast(new COMP); p->x = tmp1.x - tmp2.x; p->y = tmp1.y - tmp2.y; return p; } COMP * operator *(COMP &tmp1,COMP &tmp2) { COMP *p = static_cast(new COMP); p->x = tmp1.x*tmp2.x - tmp1.y*tmp2.y; p->y = tmp1.x*tmp2.y + tmp1.y*tmp2.x; return p; } int main() { COMP x,y; init(x,1,2); init(y,3,4); cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3