单例继承链接器错误

发布于 2024-12-10 05:11:30 字数 577 浏览 2 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静若繁花 2024-12-17 05:11:30

您错过了:

template<typename T>
T Singleton<T>::instance;

在类定义之后插入这些行。

为了初始化静态数据成员,我们必须包含一个正式的
定义在类之外,在全局范围内。

有关详细信息,请阅读此链接(部分:静态成员)

You missed:

template<typename T>
T Singleton<T>::instance;

Insert those lines after your class definition.

In order to initialize a static data-member we must include a formal
definition outside the class, in the global scope.

For more information read this link (Section: Static members)

迟到的我 2024-12-17 05:11:30

您需要在代码中的某个位置实际定义 static 变量 DebugLog Singleton::instance 的实例,您只是声明它存在于某个位置,但从未真正创建它存在。链接器正在寻找它。

这是一些 如何正确执行此操作的示例

You need to actually define an instance of the static variable DebugLog 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文