1

我遇到了如下代码,它基本上是一个单例类的示例,我们将类构造函数设为私有,并提供一个静态公共函数来在需要时创建类的实例。

我的问题是,当我们new在静态函数内部调用运算符创建单例类的对象时,肯定会调用该类的构造函数。我很困惑它是如何发生的,因为据我所知,静态函数只能访问类的静态成员和静态函数。那么它如何访问一个类的私有函数(构造函数)?

静态函数可以在不创建任何实例的情况下调用类的任何私有或公共成员函数吗?

#include <iostream>

using namespace std;

class Singleton
{
public:
    static Singleton *getInstance(); 

private:
    Singleton(){}
    static Singleton* instance;
};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance() 
{
    if(!instance) {
        instance = new Singleton(); //private ctor will be called
        cout << "getInstance(): First instance\n";
        return instance;
    }
    else {
        cout << "getInstance(): previous instance\n";
        return instance;
    }
}

int main()
{
    Singleton *s1 = Singleton::getInstance();
    Singleton *s2 = Singleton::getInstance();
    return 0;
}

但是当我编写如下示例代码时:

class Sample
{
    private:
        void testFunc()
        {
            std::cout << "Inside private function" <<std::endl;
        }
    public:
        static void statFunc()
        {
            std::cout << "Inside static function" <<std::endl;
            testFunc();
        }
};

int main()
{
    Sample::statFunc();

    return 0;
}

我收到 g++ 的编译错误:

file.cpp: In static member function ‘static void Sample::statFunc()’:
file.cpp:61: error: cannot call member function ‘void Sample::testFunc()’ without object. 

如果我们可以使用静态公共函数访问类的私有函数,那么为什么会出现此错误?

4

3 回答 3

1

静态函数可以在不创建任何实例的情况下调用类的任何私有或公共成员函数吗?

正在创建一个实例。

instance = new Singleton();

new关键字创建一个Singleton对象。

而且,是的,因为Singleton::getInstance它是类的成员函数,所以它有能力调用构造函数(尽管注意你只是间接地这样做),不管它是static不是。

于 2016-11-21T13:57:16.213 回答
1

上面代码起作用的原因是getInstance()调用构造函数的实现不需要对象的实例。

静态成员函数属于类而不是对象。因此,在调用静态成员函数时没有对象的实例,您无法访问this指针,因为没有一个。如果要从静态函数访问非静态私有成员函数,则需要将对象的引用传递给函数。例如

例如

class foo {
    public:
          foo(int i) : myInt(i) {}
          static int myStaticMethod(foo & obj);
    private:
          int myInt;
    };

    int foo::myStaticMethod(foo & obj) {
          return obj.myInt;
    }

#include <iostream>


int main() {
foo f(1);
std::cout << foo::myStaticMethod(f);
return 0;
};
于 2016-11-21T14:30:58.353 回答
0

回答您稍后添加的问题的第二部分:

class Sample
{
private:
  void testFunc()
  {
    std::cout << "Inside private function" << std::endl;
  }
public:
  static void statFunc()
  {
    std::cout << "Inside static function" << std::endl;

    Sample s;
    s.testFunc();          // this is OK, there is an object (s) and we call 
                           // testFunc upon s

    // testFunc();         // this is not OK, there is no object
  }
  void InstanceFunction()
  {
    std::cout << "Inside public instance function" << std::endl;
    testFunc();
  }
};


int main()
{
  Sample s;
  s.InstanceFunction();

  Sample::statFunc();
  return 0;
}

无法testFunc();从内部调用,因为(私有或非私有)是一个实例函数,您需要一个可以操作的对象,但它是一个函数,因此没有对象。statFunctestFuncSampletestFuncstatFuncstaticSample

错误消息对此非常清楚。

仅当您提供对象时才能调用testFuncfrom ,请参见上面的代码。statFunc

于 2016-11-21T14:16:18.517 回答