Can a Static method access a private method of the same class?

前端 未结 5 1276
一个人的身影
一个人的身影 2020-12-10 01:15

I have this question because of the singleton/named constructor. In both cases, the real constructors are protected or private, neither of which can be accessed from outside

5条回答
  •  独厮守ぢ
    2020-12-10 01:51

    Yes, it can. The static function can access private members, but other than that it is just like any function defined outside of the class. Especially, since it doesn't have a this pointer (ie. is not "bound" to any specific instance), you won't be able to access any members directly (which are always "bound" to an instance): if you wanted to do that, you need a an instance from somewhere:

    #include 
    using namespace std;
    
    class A
    {
      public:
        static A createA() { return A(0); }
        static void dosomething(A *a) { return a->something(); }
      private:
        A (int x) { cout << "ctor" << endl; }
        void something() { cout << "something" << endl; }
    };
    
    int main(void)
    {
       A a = A::createA(); 
       A::dosomething(&a); 
       return 0;
    }
    

提交回复
热议问题