其实封装并不是编程中的一个思想对于很多领域来说都是这样。对于电子器件来说我们不关心其内部的结构只在乎该器件能够实现什么样的功能。这样对于顾客来说不用花时间研究内部的实现过程而对于商家来说也可以更好的保护它们的商业秘密。而对于 C 来说也是这样借由数据类型也可以实现封装。这样做的好处就是对外屏蔽了功能实现对内开放了数据权限。C 中的类和对象是经由 C 中的 struct 发展而来的就好像 struct 是由数组发展而来的一样。因此我们可以先通过 struct 实现封装。封装实现12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#include iostreamusingstd::cout;usingstd::endl;typedefstructcomplex{intx;inty;}COMP;voidinit(COMP tmp,intx,inty){tmp.x x;tmp.y y;}COMP * operator (COMP tmp1,COMP tmp2){COMP *p static_castCOMP *(newCOMP);p-x tmp1.x tmp2.x;p-y tmp1.y tmp2.y;returnp;}COMP * operator -(COMP tmp1,COMP tmp2){COMP *p static_castCOMP *(newCOMP);p-x tmp1.x - tmp2.x;p-y tmp1.y - tmp2.y;returnp;}COMP * operator *(COMP tmp1,COMP tmp2){COMP *p static_castCOMP *(newCOMP);p-x tmp1.x*tmp2.x - tmp1.y*tmp2.y;p-y tmp1.x*tmp2.y tmp1.y*tmp2.x;returnp;}intmain(){COMP x,y;init(x,1,2);init(y,3,4);coutx.x x.yendl;couty.x y.yendl;COMP *z;z xy;coutz-x z-yendl;deletez;z x-y;coutz-x z-yendl;deletez;z x*y;coutz-x z-yendl;deletez;return0;}结果为1 23 44 6-2 -2-5 10上面的程序使用 struct 构建了类似复数的结果并使用运算符重载实现了复数的加、减、乘运算。这样如果我们要进行复数的运算的话可以直接使用 -* 而不用具体关心内部的实现过程因为我们在意的只是结果的正确性。封装属性封装的作用就像之前提到的那样对外提供接口对内提供数据。虽然上边的函数在全局构建了接口函数但是却也暴露了函数的实现过程并且我们还能够在外部直接访问 struct 内的数据这并不是我们想要的封装形式。这是由 struct 的性质决定的在 C 中提供了 class 的形式实现整个的封装过程。struct 和 class 的不同在于struct 中的数据和方法都是 public 的而 class 中的数据和方法却是可以自定义的属性内部外部publicyesyesprotectedyesnoprivateyesnoprotected 和 private 的区别在继承形式上。class 封装对于上边的 complex如果使用 class 来封装123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#include iostreamusingstd::cout;usingstd::endl;classcomplex{public:complex(){this-x 0;this-y 0;}complex(intx,inty):x(x),y(y){}complex * operator (complex tmp){complex *p static_castcomplex *(newcomplex);p-x this-x tmp.x;p-y this-y tmp.y;returnp;}complex * operator -(complex tmp){complex *p static_castcomplex *(newcomplex);p-x this-x - tmp.x;p-y this-y - tmp.y;returnp;}complex * operator *(complex tmp){complex *p static_castcomplex *(newcomplex);p-x this-x*tmp.x -this-y*tmp.y;p-y this-x*tmp.y this-y*tmp.x;returnp;}voiddisplay(){coutthis-x this-yendl;}private:intx;inty;};intmain(){complex x(1,2),y(3,4);x.display();y.display();complex *z;z xy;z-display();deletez;z x-y;z-display();deletez;z x*y;z-display();deletez;return0;}结果为1 23 44 6-2 -2-5 10上边的程序使用 class 的概念封装了 complex 的形式该形式下能够从外部调用对象的方法但是却不能够从外部访问对象的数据达到了封装的要求。