C++ question collection

Insert image description here
No, static variables in a class do not have to be public. publicThe access control permissions ( , privateor ) of static member variables protectedare the same as non-static member variables and can be determined according to design needs.

The access permission of a static member variable refers to whether the static member variable can be directly accessed outside the class. This permission setting is implemented in the class definition through the access modifier ( public, privateor ).protected

For example, a static member variable of a class can be private, which means that only the member functions of the class can access it and cannot be accessed directly from outside the class. Examples are as follows:

class MyClass {
    
    
private:
    static int myStaticVar;

public:
    // 成员函数可以访问静态成员变量
    void setStaticVar(int value) {
    
    
        myStaticVar = value;
    }
};

int MyClass::myStaticVar = 0;  // 静态变量的初始化

int main() {
    
    
    MyClass obj;
    obj.setStaticVar(42);  // 调用类的成员函数设置静态变量的值
    // obj.myStaticVar = 42;  // 这将导致编译错误,因为 myStaticVar 是 private 的
    return 0;
}

In short, the access permissions of static member variables depend on how you set their access modifiers in the class definition.

In C++, private static member variables are part of the class, but cannot be directly accessed outside the class. However, you can initialize private static member variables outside the class. This type of initialization is usually done outside the class's definition, as you saw in the previous code example.

Private static member variables are invisible to users of the class and cannot be accessed directly. But you can do it in methods inside the class, and initialize it outside the class. This approach allows you to hide implementation details and only provide a public interface for external use.

Guess you like

Origin blog.csdn.net/ZHorcrux/article/details/132295014