天天看点

扩展知识点-----数据封装的使用方法

定义上讲:数据封装是一种把数据和操作数据的函数绑定在一起的机制,数据抽象是一种仅向用户暴露接口而把具体的实现细节隐藏起来的机制。

#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;
}