尝试在 c++ 中编译单例时出现编译错误
Compilation error when trying to compile a singleton in c++
我正在尝试学习 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
相关文章:
- C++ 实现模板单例类时出现链接错误
- C++中的单例实现在调用 getInstance 函数时不会产生相同的类实例
- 在Raspbian上编译pybind11测试用例时出现致命错误
- _CrtIsValidHeapPointer(块)错误在应用单例-帕特恩后退出主窗口时引发
- 访问单例类C++时出现问题
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃
- C++在单例类中创建类实例时遇到困难
- 如何在 c++ 中使用单例模式时编写 cmake 文件
- 运行时动态加载和单例
- GDB 在单步执行单例的静态方法时没有显示这一点?
- 在进行 OOP 状态机设计时如何避免单例
- 为什么这个单例实现无法编译?
- C++懒惰的单例挂在加载时
- 在DLL中提供的ZeroMQ上下文单例在程序退出时崩溃(VS2010 win7 x64 zmq 4.0x)
- 我可以在编译期间从 gcc 获取单例的地址或链接时吗?
- 扩展具有私有构造函数和析构函数的单例类会给出编译时警告
- Qt/C++ 应用程序在从 DLL 使用单例时卡在 main() 启动之前
- 创建单例时出现错误
- 尝试在 c++ 中编译单例时出现编译错误
- 设计模式——在c++中,当实现(一组单例)直接从它们的编译单元在某个注册表中自注册时,它被称为什么?