Singleton在微控制器上

发布于 2025-01-20 16:06:59 字数 724 浏览 1 评论 0原文

我试图在嵌入式项目中使用单例模式,但无法编译该项目。现在的课程很简单,我不明白这个问题。

错误是(48,在我的代码中是实例函数的最后一行):

RadioWrapper.h:48: undefined reference to `RadioWrapper::mInstance'

有什么想法吗?

#define RADIOWRAPPER_H_

class RadioWrapper
{
protected:
    RadioWrapper() {};
    ~RadioWrapper() { mInstance = NULL;}

public:

    static RadioWrapper* instance (void)
    {
        if (!mInstance)
        {
            mInstance = new RadioWrapper();
            return mInstance;
        }
        else
        {
            return mInstance;
        }
    }

    void setRx (void);

private:
    static RadioWrapper* mInstance;

};

#endif /* RADIOWRAPPER_H_ */

I am trying to use Singleton pattern in an embedded project, but I can't compile the project. The class, now, is very simple and I don't understand the problem.

The error is (48, in my code is the last line of instance function):

RadioWrapper.h:48: undefined reference to `RadioWrapper::mInstance'

Any ideas?

#define RADIOWRAPPER_H_

class RadioWrapper
{
protected:
    RadioWrapper() {};
    ~RadioWrapper() { mInstance = NULL;}

public:

    static RadioWrapper* instance (void)
    {
        if (!mInstance)
        {
            mInstance = new RadioWrapper();
            return mInstance;
        }
        else
        {
            return mInstance;
        }
    }

    void setRx (void);

private:
    static RadioWrapper* mInstance;

};

#endif /* RADIOWRAPPER_H_ */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

淡看悲欢离合 2025-01-27 16:06:59

类的静态成员,如static RadioWrapper* mInstance
必须定义(H 文件中的内容只是声明)。

您需要添加:(

/*static*/ RadioWrapper::mInstance = nullptr;

/*static*/ 前缀仅用于文档)。

应将其添加到 CPP 文件中,而不是 H 文件中(否则,如果多次包含 H 文件,您将有多个定义。)

如果您使用的是 C++ 17,则可以使用 内联 可以在H文件中定义和初始化的变量。请参阅此处的第二个答案:如何初始化标头中的静态成员

A static member of a class, like static RadioWrapper* mInstance,
has to be defined (what you have in the H file is a declaration only).

You need to add:

/*static*/ RadioWrapper::mInstance = nullptr;

(the /*static*/ prefix is for documentation only).

This should be added in a CPP file, not H file (otherwise if the H file is included more than once, you'll have multiple definitions.)

If you are using C++ 17, you can use an inline variable that can be defined and initialized in the H file. See the 2nd answer here: How to initialize static members in the header

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