定义上讲:数据封装是一种把数据和操作数据的函数绑定在一起的机制,数据抽象是一种仅向用户暴露接口而把具体的实现细节隐藏起来的机制。
#include <iostream>
#include <string>
using namespace std;
class Dog
{
public:
string name;
Dog(int i = 0)
{
total = i;
}
void addFood(int number){
total = total + number;
}
int getFood(){
return total;
}
private:
int total;
};
int main()
{
Dog dog;
dog.name = "小狗";
dog.addFood(3);
dog.addFood(2);
cout << dog.name << "总共获得了" << dog.getFood() << “”食物“”<< endl;
return 0;
}
解释:Dog(int i=0)是构造函数,一般用来初始化
以上代码可以使用Linux中g++进行编译 例如:g++ xxxx.cpp -o test 运行时./test
总结:该函数体现了数据封装中如何访问类中私有成员的方法,把数据和操作数据的函数绑定在一起。