C++的封装

序言

此篇文章用于记录学习C++的封装,包括如下只是:对比C语言的封装,以队列为实例使用C++的封装。

C语言的封装

C语言可以通过结构体将多个类型的数据打包成一体,形成新的类型,然后将数据通过指针传给行为,这就是C语言的封装。

#include <stdio.h>
typedef struct Date
{
	int year;
	int month;
	int day;
}date;
void init(date* d)  //形参为结构体指针
{
	d->year = 2012;
	d->month = 12;
	d->day = 12;
}
void printvalue(date* d)  //形参为结构体指针
{
	printf("ending date %d:%d:%d\n",d->year,d->month,d->day);
}
int main()
{
	date d;  //结构体类型
	init(&d);  //对结构体取地址,类型为结构体指针
	//d.year = 2011; 这里是可以改变数值的,C语言的封装并不好
	printvalue(&d);
    return 0;
}

C++的封装

封装:对外提供接口,对内开放数据,
C语言的struct封装,既可以知其接口,又可以直接访问内部数据,C语言的封装是没有达到信息屏蔽的功效。
C++使用class提供封装,class可以指定行为和属性的访问方式(public,private,protected)

实例:以对队列的操作,使用C++来封装
包含三个文件:stack.cpp stack.h stackmain.cpp

stack.h

#include <iostream>
namespace Stack{
	class stack
	{
		private:
			char space[1024];
			int top;
		public:
			void init();
			bool isEmpty();
			bool isFull();
			char pop();
			void push(char c);
	};
}

stack.cpp

#include <iostream>
#include "stack.h"
#include <string.h>
using namespace std;
namespace Stack{
	void stack::init()
	{
		top = 0;
		memset(space,0,1024);
	} 
	bool stack::isEmpty()
	{
		return top == 0;
	}
	bool stack::isFull()
	{
		return top == 1024;
	}
	char stack::pop()
	{
		char c = space[--top];
		return c;
	}
	void stack::push(char c)
	{
		space[top++] = c;
	}
}

stackmain.cpp

#include <iostream>
#include "stack.h"
using namespace std;
using namespace Stack;
int main()
{
	stack s;
	s.init();
	if(!s.isFull())
		s.push('a');
	if(!s.isFull())
		s.push('b');
	if(!s.isFull())
		s.push('c');
	while(!s.isEmpty())
		cout<<s.pop()<<endl;
	return 0;
}

测试结果:
编译:g++ stackmain.cpp stack.cpp -o stack

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值