我遇到的代碼來了,如同下面,這基本上是我們使類的構造私人和提供一個靜態公共函數創建一個單獨的類的實例的私有成員函數(構造函數)需要時的課程實例。如何靜態函數訪問類
我的問題是當我們調用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'類的成員,因此它可以調用該類的所有方法,甚至是私有方法。 –