我遇到了如下代码,它基本上是一个单例类的示例,我们将类构造函数设为私有,并提供一个静态公共函数来在需要时创建类的实例。
我的问题是,当我们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.
如果我们可以使用静态公共函数访问类的私有函数,那么为什么会出现此错误?