Mil*_*avi -1 c++ singleton design-patterns linker-errors
我正在尝试将此java单例类移植到c ++:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
我移植到这个C++代码:
class Singleton {
private:
Singleton() {
cout << "new Singleton is called" << endl;
}
static Singleton* uniqueInstance;
public:
static Singleton* getInstance() {
if (!uniqueInstance) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
};
Run Code Online (Sandbox Code Playgroud)
但是我无法编译这个!和gcc链接器发生错误.
确保static在声明之外定义成员:
Singleton* Singleton::uniqueInstance = nullptr;
Run Code Online (Sandbox Code Playgroud)