0
    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();
      }

Question : How can setfunc() can be called in another function without using that class object. Also, if it changes like setting value of "_a" via someclass B. the same value of will persist whenever I try to retrieve it in someanother class like C via getValue()

4

1 回答 1

3

在静态函数中,您只能使用类的静态成员。像这样(_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!
};
于 2013-06-13T19:55:10.653 回答