单例继承链接器错误
我是 C++ 新手,我遇到了这个链接器错误,
LNK2001:无法解析的外部符号“私有:静态类 DebugLog Singleton::instance”(?instance@?$Singleton@VDebugLog@@@@0VDebugLog@@A)
这是有问题的代码:
template<typename T>
class Singleton {
public:
static T& getInstance() {
return instance;
}
private:
static T instance;
};
class DebugLog : public Singleton<DebugLog> {
public:
void doNothing() {}
};
void main() {
DebugLog::getInstance().doNothing();
}
有人能告诉我如何解决这个问题吗?链接器错误而不丢失 DebugLog 中的单例继承?
谢谢。
I'm new with C++, and I got this linker error,
LNK2001: unresolved external symbol "private: static class DebugLog Singleton::instance" (?instance@?$Singleton@VDebugLog@@@@0VDebugLog@@A)
And here is the problematic codes:
template<typename T>
class Singleton {
public:
static T& getInstance() {
return instance;
}
private:
static T instance;
};
class DebugLog : public Singleton<DebugLog> {
public:
void doNothing() {}
};
void main() {
DebugLog::getInstance().doNothing();
}
Could anybody tell me how I can fix that linker error without losing the Singleton inheritance in DebugLog?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(2)
您错过了:
在类定义之后插入这些行。
有关详细信息,请阅读此链接(部分:静态成员)
You missed:
Insert those lines after your class definition.
For more information read this link (Section: Static members)
您需要在代码中的某个位置实际定义
static
变量DebugLog Singleton::instance
的实例,您只是声明它存在于某个位置,但从未真正创建它存在。链接器正在寻找它。这是一些 如何正确执行此操作的示例。
You need to actually define an instance of the
static
variableDebugLog Singleton::instance
somewhere in your code, you just declared that it exists somewhere, but never actually created it to really exist. The linker is looking for it.Here's some examples of how to do it right.