为什么我必须在这行声明类型?
Why do I have to declare type at this line
我正在读一本关于c++中单例的书
在这本书中,有一个例子展示了如何编写单例:
// Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
#endif //~_SINGLETON_H_
这是它对应的cpp文件
// Singleton.cpp
#include "Singleton.h"
Singleton* Singleton::_instance = 0; // why do I have to type "Singleton*" at this line?
Singleton::Singleton()
{
cout << "Singleton..." << endl;
}
Singleton* Singleton::Instance()
{
if (_instance == 0)
{
_instance = new Singleton();
}
return _instance;
}
让我困惑的是"Singleton* Singleton::_instance = 0;"这一行。
我认为写"Singleton::_instance = 0;"足以让c++编译器理解。因为我已经在头文件中声明了"静态Singleton* _instance;"。
为什么我必须第二次声明_instance是Singleton*类型?
我试过删除"Singleton*"。删除后,Visual Studio告诉我
"错误C4430:缺少类型说明符-假定为int。"
尽管其他答案中所说的是正确的,但我建议您使用以下实现
Singleton& Singleton::Instance() {
static Singleton theInstance;
return theInstance;
}
这个习惯用法不仅是线程安全的,而且它更少写,关于你关于_instance
变量的声明和定义的观点
你可能不喜欢这个答案,但要点是c++只是要求在所有定义中指定类型(在某些特殊情况下,你可以使用auto
)。
与声明和定义函数时需要重复类型的原因相同:
int foo(char);
int foo(char x) {
return x;
}
简短的回答是,任何声明的类型必须与其定义的类型匹配。如果你不明白声明和定义之间的区别,我建议你做一些研究和阅读。
相关文章:
- std::enable_if 更改成员 *变量* 声明/类型
- 对前向声明类型进行unique_ptr的解决方法
- 如何将声明类型作为参数发送
- 在 Fortran 中泛化特定声明类型的操作
- 使用 (c++11) 声明类型时放置 __declspec(dllimport) 关键字的位置
- 模板函数可以使用带有删除的构造函数的声明类型
- 声明类型没有任何可变类型
- 如何使用声明类型简化此代码
- 使用声明类型选择函数专业化
- 替代班级内声明类型的别名
- 对于自动键入推论的参数,声明类型(自动)应推导的内容
- 使用 decltype 的条件声明类型
- 您如何声明类型结构的堆栈?在C 中
- 将指向前向声明类型的指针推送到 typedef'd 向量时出现编译器错误
- 声明适用于 auto,但不能显式声明类型?
- 声明类型包含未展开的参数包'Args'
- 课堂上的Typedef.在另一个类错误中:尚未声明类型
- 冲突的声明类型/价值不匹配
- 获取具有AST访问者clang的功能声明类型
- 变量声明类型定义 C 中的约定