从struct说起
- 当单一变量无法完成描述需求的时候,结构体类型解决了这一问题。可以将多个类型
打包成一体,形成新的类型。这是 c 语言中封装的概念。 - 新类型并不包含,对数据类的操作,所的有操作都是通过函数的方式
- C语言struct例子:
#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);
d.year = 2017;
if(isLeapYear(d))
cout<<"leap year"<<endl;
else
cout<<"not leap year"<<endl;
return 0;
}
封装的访问属性

- struct 中所有行为和属性都是 public 的(默认)。C++中的 class 可以指定行为和属性的
访问方式。 - 我们用 struct 封装的类,即知其接口,又可以直接访问其内部数据,这样却没有达到信息隐蔽的功效。而 class 则提供了这样的功能,屏蔽内部数据,对外开放接口。
用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;
}