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