1、封装
c++c是通过类来实现封装的,把这些数据和数据有关的操作封装在一个类中,或者说类的作用就是把数据和算法封装在用户声明的抽象数据类型中。
2、限定符
public:公共的
private:私有的
protected:受保护的
3、封装实例
#include<iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Student //声明一个类
{
public:
void setName(string _name)//设置名字
{
m_strName=_name;
}
string getName()//得到名字
{
return m_strName;
}
void setGender(string _gender)//设置性别
{
m_strGender=_gender;
}
string getGender()//得到性别
{
return m_strGender;
}
int getScore()//得到分数,属于只读
{
return m_iScore;
}
void initScore()//初始化分数
{
m_iScore=0;
}
void study(int _score)//通过学习获得分数
{
m_iScore+=_score;
}
private:
string m_strName;//姓名
string m_strGender;//性别
int m_iScore;//分数
};
int main()
{
Student stu;
stu.initScore();
stu.setName("zhangshan");
stu.setGender("男");
stu.study(4);
stu.study(6);
cout<<stu.getName()<<""<<stu.getGender()<<""<<stu.getScore()<<endl;
system("pause");
return 0;
}