gpt4 book ai didi

c++ - 对单例模式的这方面感到困惑

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:05 26 4
gpt4 key购买 nike

我根据在网上找到的教程改编了我的 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;”然后我得到一个错误。既然已经在header中声明了,为什么还要再提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-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator.

更新,回应 OP 的评论

假设你有:

namespace detail
{
class Foo
{
static int var;
};
}

Foo::var 必须在 Foo 的封闭 namespace 中定义。

namespace detail
{
int Foo:var = 0;
}

在类没有显式封闭命名空间的情况下,全局作用域就是它的封闭命名空间。

关于c++ - 对单例模式的这方面感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26923781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com