尝试在 c++ 中编译单例时出现编译错误

Compilation error when trying to compile a singleton in c++

本文关键字:编译 单例时 错误 c++      更新时间:2023-10-16

我正在尝试学习 c++。我写了一个文件"Singleton.h",如下所示:

class Singleton
{
private:
    static Singleton* m_this;
    Singleton();
public: 
    static Singleton* getInstance(){
        return m_this;
    }
    virtual ~Singleton();
};

我的单例.cpp文件:

#include "StdAfx.h"
#include "Singleton.h"
Singleton::Singleton(){}
Singleton::~Singleton(){}

我调用我的主方法来获取getInstance方法,如下所示:

Singleton* s = NULL;
s = Singleton.getInstance();

但是,我收到编译错误:

error C2275: 'Singleton' : illegal use of this type as an expression

你知道这是为什么吗?

s = Singleton::getInstance();

不是.,而是静态方法的::(范围解析运算符)。

使用范围解析运算符

 s = Singleton::getInstance();

你应该使用类似Singleton::调用

Singleton* s = NULL;
s = Singleton::getInstance();

作用域运算符::而不是.

另外,您将收到链接错误,您需要添加

Singleton* Singleton::m_this;

到辛格尔顿.cpp

但最好改用namespace