How access class variables in c++

前端 未结 4 1728
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 00:44

Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable. I

4条回答
  •  清酒与你
    2021-01-20 01:16

    static is the right keyword here:

    class A {
    public:
      static int i; // <-- this is a class variable
    };
    
    class B {
    public:
      void f() { A::i = 3; } // <-- this is how you access class variables
    };
    

    They only potential problem I can think of is that

    1. You made the class variable protected or private, thus rendering it inaccessible from other code.
    2. You forgot to specify the full scope of the class variable (with A:: in this example).

提交回复
热议问题