为什么我必须在这行声明类型?

Why do I have to declare type at this line

本文关键字:声明 类型 为什么      更新时间:2023-10-16

我正在读一本关于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;
}

简短的回答是,任何声明的类型必须与其定义的类型匹配。如果你不明白声明和定义之间的区别,我建议你做一些研究和阅读。