我遇到的代码来了,如同下面,这基本上是我们使类的构造私人和提供一个静态公共函数创建一个单独的类的实例的私有成员函数(构造函数)需要时的课程实例。如何静态函数访问类
我的问题是当我们调用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.
如果我们可以用静态公网访问类的私有函数函数那么为什么我得到这个错误?
简答:恕我直言,是的。恕我直言,你的代码没有问题。 'getInstance'是'Singleton'类的成员,因此它可以调用该类的所有方法,甚至是私有方法。 –