2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Encapsulation is one of the three basic characteristics of object-oriented programming (OOP) (encapsulation, inheritance, polymorphism). It refers to combining data (attributes) and methods (functions) that operate on these data into an independent unit (class), hiding the internal details of the object as much as possible, and only exposing the interface to the outside world. The purpose of this is to protect the object's data, prevent external code from directly accessing the object's internal data structure, reduce errors and simplify complexity.
Using Class: When defining a class, set the data members (attributes) to private or protected, and set the methods that operate on these data to public. In this way, external code cannot directly access the private members of the class, but can only access them indirectly through public methods.
Access Modifiers:
public
: Any external code can access.protected
: Can only be accessed in the class itself and derived classes (subclasses).private
: Can only be accessed in the class itself, not in derived classes.Constructors and Destructors: Initialize the object through the constructor and clean up the resources occupied by the object through the destructor. They are also part of encapsulation because they control the life cycle of the object.
The following is a simple C++ wrapper example showing aRectangle
Implementation of the (Rectangle) class.
- #include <iostream>
-
- class Rectangle {
- private:
- double width; // 矩形的宽
- double height; // 矩形的高
-
- public:
- // 构造函数
- Rectangle(double w, double h) : width(w), height(h) {}
-
- // 设置宽度
- void setWidth(double w) {
- width = w;
- }
-
- // 获取宽度
- double getWidth() const {
- return width;
- }
-
- // 设置高度
- void setHeight(double h) {
- height = h;
- }
-
- // 获取高度
- double getHeight() const {
- return height;
- }
-
- // 计算面积
- double getArea() const {
- return width * height;
- }
- };
-
- int main() {
- Rectangle rect(5.0, 10.0);
- std::cout << "Rectangle area: " << rect.getArea() << std::endl;
- rect.setWidth(7.0);
- std::cout << "New Rectangle area: " << rect.getArea() << std::endl;
- return 0;
- }
In this example,Rectangle
Classwidth
andheight
Properties are made private so that external code cannot access them directly. Instead, we access them through public methods such assetWidth
、getHeight
andgetArea
) to access and modify these private properties. This approach implements data encapsulation and provides a clear interface for external use.