How is the keyword “public” used in C++?

In C++, public is an access modifier used to specify the visibility of a class’s members (member variables and member functions) to external code. When a member is declared as public, these members can be accessed and invoked directly by the class’s objects or external code.

Specifically, using the “public” keyword can declare a class member as a public member, making these members visible and accessible to external code. For example:

class MyClass {
public:
    int publicVar; // 公有成员变量
    void publicFunc() { // 公有成员函数
        // 函数体
    }
};

In the example above, publicVar and publicFunc are declared as public members, allowing them to be directly accessed and called in the class’s objects or external code. This design makes the class’s interface clearer and also provides control and encapsulation of the public parts of the class.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds