C++之封装

C++面向对象有三大特性,封装,继承和派生。今天我们来了解一下封装。
1.先从struct说起
    当单一变量无法完成描述需求的时候,结构体类型解决了这一问题。可以将多个类型打包成一体,形成新的类型。这是c 语言中封装的概念。但是,新类型并不包含,对数据类的操作。所的有操作都是通过函数的方式,去其进行封装。
例如:

#include <iostream>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
void init(Date &d)
{
cout<<"year,month,day:"<<endl;
cin>>d.year>>d.month>>d.day;
}
void print(Date & d)
{
cout<<"year month day"<<endl;
cout<<d.year<<":"<<d.month<<":"<<d.day<<endl;
}
bool isLeapYear(Date & d)
{
if((d.year%4==0&& d.year%100 != 0) || d.year%400 == 0)
     return true;
else  return false;
}
int main()
{
Date d;
init(d);
print(d);
if(isLeapYear(d))
cout<<"leap year"<<endl;
else
cout<<"not leap year"<<endl;
return 0;
}

2.封装
封装,可以达到,对外提供接口,屏蔽数据,对内开放数据。
    比如我们用struct 封装的类,即知其接口,又可以直接访问其内部数据,这样却没有达到信息隐蔽的功效。而class 则提供了这样的功能,屏蔽内部数据,对外开放接口。struct 中所有行为和属性都是public 的(默认)。C++中的class 可以指定行为和属性的访问方式,默认为pirvate,即class的内部数据成员在外部不能访问。
访问方式
class 封装的本质,在于将数据和行为,绑定在一起然后通过对象来完成操作
例如:

#include <iostream>
using namespace std;
class Date
{public:
void init();
void print();
bool isLeapYear();
private:
int year;
int month;
int day;
};
void Date::init()
{
cout<<"year,month,day:"<<endl;
cin>>year>>month>>day;
}
void Date::print()
{
cout<<"year month day"<<endl;
cout<<year<<":"<<month<<":"<<day<<endl;
}
bool Date::isLeapYear()
{
if((year%4==0&& year%100 != 0) || year%400 == 0)
     return true;
else return false
}
int main()
{
Date d;
d.init();
d.print();
if(d.isLeapYear())
cout<<"leap year"<<endl;
else
cout<<"not leap year"<<endl;
return 0;
}

自此c++面向对象的三大特性之一封装就讲完了。跟struct很相似,只不过struct默认是公有的,只包含数据不包含行为,而class默认是私有的,包含数据和行为,记住这些就足够了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值