💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# C++ 封装 > 原文: [https://beginnersbook.com/2017/09/cpp-encapsulation/](https://beginnersbook.com/2017/09/cpp-encapsulation/) 封装是将数据成员和函数组合在一个称为类的单个单元中的过程。这是为了防止直接访问数据,通过类的函数提供对它们的访问。它是[面向对象编程(OOP)](https://beginnersbook.com/2017/08/cpp-oops-concepts/)的流行特性之一,它有助于**数据隐藏**。 ## 如何在类上实现封装 为此: 1)将所有数据成员设为私有。 2)为每个数据成员创建公共设置器和获取器函数,使设置器设置数据成员的值,获取器获取数据成员的值。 让我们在一个示例程序中看到这个: ## C++ 中的封装示例 这里我们有两个数据成员`num`和`ch`,我们已将它们声明为私有,因此它们在类外无法访问,这样我们就隐藏了数据。获取和设置这些数据成员的值的唯一方法是通过公共设置器和获取器函数。 ```cpp #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; } ``` **输出:** ```cpp 100 A ```