1、C语言中的struct数据封装
C语言中用结构体关键字Struct将多个类型打包成一体,形成新的类型。
缺点:新类型不包含对数据的操作。所有的操作都是通过函数传参的方式,去进行封装。
如何做到数据和行为统一: 以Stack为例,将数据(空间、游标),行为(压入、弹出、判空、判满)打包到结构体中。
#include <iostream>
#include <string.h>
using namespace std;
struct Stack
{
int space[1024];
int top;
};
void init(Stack& s)
{
memset(s.space, 0, sizeof(s.space));
s.top = 0;
}
bool IsEmpty(Stack& s)
{
return s.top == 0;
}
bool is_full(Stack& s)
{
return s.top == 1024;
}
void push(Stack& s, int data)
{
s.space[s.top] = data;
s.top++;
}
int pop(Stack& s)
{
return s.space[--s.top];
}
int main()
{
Stack s;
init(s);
if(!is_full(s))
{
push(s,10);
}
if(!is_full(s))
{
push(s,20);
}
if(!is_full(s))
{
push(s,30);
}
if(!is_full(s))
{
push(s,40);
}
if(!is_full(s))
{
push(s,50);
}
while (!IsEmpty(s))
{
cout<<pop(s)<<endl;
}
return 0;
}
2、C++的class
struct封装的所有行为和数据,均是public,即均可通过对象直接访问。class引入了成员权限控制机制。
class的优点:对外提供接口,屏蔽数据。对内开放数据。
#include <iostream>
#include <string.h>
using namespace std;
class Stack
{
public:
void init();
bool isEmpty();
bool isFull();
void push(int data);
int pop();
private:
int space[1024];
int top;
};
void Stack::init()
{
memset(space, 0, sizeof(space));
top = 0;
}
bool Stack::isEmpty()
{
return top == 0;
}
bool Stack::isFull()
{
return top == 1024;
}
void Stack::push(int data)
{
space[top++] = data;
}
int Stack::pop()
{
return space[--top];
}
int main()
{
Stack s;
s.init();
if (!s.isFull())
s.push(10);
if (!s.isFull())
s.push(20);
if (!s.isFull())
s.push(30);
if (!s.isFull())
s.push(40);
while (!s.isEmpty())
cout << s.pop() << endl;
return 0;
}
::域运算符,常见于命名空间。此时也用在了类的成员函数上,
意指类名也是一个小的
作用域命名空间
,其作用域内包装了全局成员与函数。
3、构造器
将上例中,init 函数,注释掉。换成与类名相同的函数,该函数无返回,称为构造函
数,会在对象构造的时候,自动调用。
与类名同的无返回值函数,在类对象创建时(堆/栈对象),自动调用,完成类对象的初
始化。尤其是动态堆内存的申请。
class 类名
{
类名(形式参数)
构造体
}
class A
{
A(形式参数)
{
}
}
class Stack
{
public:
Stack(int size)
{
top = 0;
_size = size;
space = new int[_size]{0};
}
}
构造规则:
1、与类名同,在对象创建时自动调用,完成初始化相关的工作。
2、无返回值,可带参数,可以重载,可默认参数。
3、默认无参空实现体,一经自实现,默认不复存在。