静态关键字在这里有帮助吗?

Will static keyword helps here

本文关键字:有帮助 在这里 关键字 静态      更新时间:2023-10-16
    class A{
    int _a;
    public:
    /--/ void setfunc(int a)        ............. will static works here
    {
      _a=a;
    }
     int getValue(){return _a};
    };
    class B{
     public:
     void func()
     {
      /--/ setfunc(1);          ...................Dont want to create object of A.
     }
    };
    class C{
     public:
       void something()
       {
        A aa;
        cout<<aa.getValue();            ............. want a value update by                      class B setfunc
       }
     };
     int main()
      {
        B bb;
        bb.func();
        C cc;
        cc.something();
      }

问题:setfunc()如何在另一个函数中调用而不使用该类对象?此外,如果它改变了,比如通过某些类b设置"_a"的值,当我试图通过getValue()

在其他类(如C)中检索它时,相同的值将持续存在

在静态函数中只能使用类的静态成员。像这样(_a是静态的):

class A {
    static int _a;
    public:
    static void setfunc(int a)
    {
      _a=a;
    }
    static int getValue(){return _a};
};

否则,你不能对非静态成员做任何事情:

class A {
    int _a;
    public:
    static void setfunc(int a)
    {
      _a=a; // Error!
    }
    static int getValue(){return _a}; // Error!
};
相关文章: