封装是将数据成员和函数组合在一个称为类的单个单元中的过程。这是为了防止直接访问数据,通过类的函数提供对它们的访问。它是面向对象编程(OOP)的流行特性之一,它有助于数据隐藏。
如何在类上实现封装
为此:
1)将所有数据成员设为私有。
2)为每个数据成员创建公共设置器和获取器函数,使设置器设置数据成员的值,获取器获取数据成员的值。
让我们在一个示例程序中看到这个:
C++ 中的封装示例
这里我们有两个数据成员num和ch,我们已将它们声明为私有,因此它们在类外无法访问,这样我们就隐藏了数据。获取和设置这些数据成员的值的唯一方法是通过公共设置器和获取器函数。
#include<iostream>using namespace std;class ExampleEncap{private: /* Since we have marked these data members private, * any entity outside this class cannot access these * data members directly, they have to use getter and * setter functions. */ int num; char ch;public: /* Getter functions to get the value of data members. * Since these functions are public, they can be accessed * outside the class, thus provide the access to data members * through them */ int getNum() const { return num; } char getCh() const { return ch; } /* Setter functions, they are called for assigning the values * to the private data members. */ void setNum(int num) { this->num = num; } void setCh(char ch) { this->ch = ch; }};int main(){ ExampleEncap obj; obj.setNum(100); obj.setCh('A'); cout<<obj.getNum()<<endl; cout<<obj.getCh()<<endl; return 0;}输出:
100A
