我遇到了如下代码,这基本上是一个单例类的例子,其中我们将类构造函数设置为私有,并提供一个静态的公共函数,以便在需要时创建类的实例。
我的问题是,当我们调用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.
如果我们可以用静态的公共函数访问类的私有函数,那么为什么我会得到这个错误呢?
发布于 2016-11-21 14:30:58
上面的代码之所以工作,是因为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-21 13:57:16
静态函数可以在不创建实例的情况下调用类的任何私有或公共成员函数吗?
您正在创建一个实例。
instance = new Singleton();
new
关键字创建一个Singleton
对象。
而且,是的,因为Singleton::getInstance
是类的成员函数,所以它能够调用构造函数(尽管注意您只是间接地这样做),不管它是否是static
。
发布于 2016-11-21 14:16:18
请回答您稍后添加的问题的第二部分:
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();
内部调用statFunc
,因为testFunc
(私有或非私有)是一个实例函数,您需要一个testFunc
可以操作的Sample
对象,但是statFunc
是一个static
函数,因此没有Sample
对象。
关于这一点,错误信息非常清楚。
只有在提供对象的情况下,才能从testFunc
调用statFunc
,参见上面的代码。
https://stackoverflow.com/questions/40721770
复制相似问题