c++ learning class and objects public, protected, private

foreword

In C++, access control modifiers (Access Control Modifiers) are used to control access to members of a class (member variables and member functions). These modifiers are divided into three types: public, protected, and private. They define where members can be accessed as follows:

public:
public members are accessible both inside and outside the class.
This means that the public members of the class can be accessed directly from anywhere.
protected:

Protected members are accessible inside the class, but inaccessible outside the class.
Subclasses (derived classes) can access protected members of their parent class.
private:

Private members can only be accessed inside the class and are hidden from the outside.
Cannot be accessed by subclasses of the class.

Here is an example illustrating the use of these access control modifiers:

#include <iostream>

class MyClass {
public:
    int publicVar;       // public 成员
    void PublicMethod() {
        std::cout << "Public method." << std::endl;
    }

protected:
    int protectedVar;    // protected 成员
    void ProtectedMethod() {
        std::cout << "Protected method." << std::endl;
    }

private:
    int privateVar;      // private 成员
    void PrivateMethod() {
        std::cout << "Private method." << std::endl;
    }
};

// 上面 三种权限在这个类里面都是可以访问的

class MyDerivedClass : public MyClass {
public:
    void AccessProtected() {
        protectedVar = 42;  // 子类可以访问父类的 protected 成员
        ProtectedMethod();  // 子类可以调用父类的 protected 方法
    }
};

int main() {
    MyClass myObj;
    myObj.publicVar = 10;     // 可以直接访问 public 成员
    myObj.PublicMethod();     // 可以调用 public 方法

    // 下面的代码无法通过编译,因为 protectedVar 和 ProtectedMethod 是 protected 的
    // myObj.protectedVar = 20;
    // myObj.ProtectedMethod();

    MyDerivedClass derivedObj;
    derivedObj.AccessProtected();  // 子类可以访问 protected 成员和方法

    return 0;
}

To sum up, access control modifiers allow you to control the visibility and accessibility of members of a class to the outside world, thereby implementing the concept of encapsulation, hiding the internal implementation details of the class and providing appropriate access interfaces.

Guess you like

Origin blog.csdn.net/wniuniu_/article/details/132568198