《C++学习笔记》【封装】封装性
以下程序依靠封装,能够保证需要修改数据时才能修改,不准修改数据时就不能修改。
[例1]使用封装以便保护数据
#include <iostream.h>class integ //用户建立一个类,以便封装{ int j; //被保护的数据public: integ( ) { j = 6; } //构造函数 int sq() { return j*j; } //求平方的函数 int read() { return j; } //读数据的函数};void main(){ integ obj; //建立对象并初始化 cout << obj.read() << endl; //读数据 cout << obj.sq( ) << endl; //读平方值}