Singleton在微控制器上
我试图在嵌入式项目中使用单例模式,但无法编译该项目。现在的课程很简单,我不明白这个问题。
错误是(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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类的静态成员,如
static RadioWrapper* mInstance
,必须定义(H 文件中的内容只是声明)。
您需要添加:(
/*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:
(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