我根据在网上找到的教程改编了我的 Singleton 类。我的标题看起来像这样:
class Logger{
public:
static Logger *instance();
~Logger();
private:
Logger();
static Logger *instance_;
};
cpp 文件是:
Logger* Logger::instance_=nullptr; //Confused about this
Logger *Logger::instance(){
if (instance_==nullptr){
instance_=new Logger();
}
return instance_;
}
Logger::Logger(){}
几个问题:
1) 在我的 cpp 的第一行中,如果我只写“Logger::instance_=nullptr;”然后我得到一个错误。既然已经在头文件中声明了,为什么我还需要再次提到instance_是一个指针呢?
2) 为什么我不能将头文件本身中的instance_初始化为“static Logger *instance_=nullptr;”?这样做会出现以下错误:
error: ‘constexpr’ needed for in-class initialization of static data member ‘Logger* Logger::instance_’ of non-integral type [-fpermissive] static Logger*instance_=nullptr; ^
谢谢!
最佳答案
Question 1) In the first line of my cpp, if I write just
Logger::instance_=nullptr;
then I get an error. Since it's already been declared in the header, why do I need to mention that instance_ is a pointer again?
来自 C++ 标准草案 N3337:
9.4.2 Static data members
5
static
data members of a class in namespace scope have external linkage (3.5).
这类似于声明
extern int a;
在 .h 文件中并定义
int a = 10;
在 .cpp 文件中。定义时,您必须指定 a
的类型。
Question 2) Why can't I initialize instance_ in the header file itself as "static Logger *instance_=nullptr;"?
来自 C++ 标准草案 N3337(强调我的):
9.4.2 Static data members
2 The declaration of a
static
data member in its class definition is not a definition and may be of an incomplete type other than cv-qualifiedvoid
. The definition for astatic
data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of thestatic
data member shall be qualified by its class name using the :: operator.
更新,回应OP的评论
假设你有:
namespace detail
{
class Foo
{
static int var;
};
}
Foo::var
必须在 Foo
的封闭命名空间
中定义。
namespace detail
{
int Foo:var = 0;
}
在类没有显式封闭命名空间的情况下,全局范围是它的封闭命名空间。
关于c++ - 对单例模式的这方面感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26923781/