对静态成员变量的未定义引用
我有一个有静态成员的类。它也是我的程序中其他几个类的基类。这是它的头文件:
#ifndef YARL_OBJECT_HPP
#define YARL_OBJECT_HPP
namespace yarlObject
{
class YarlObject
{
// Member Variables
private:
static int nextID; // keeps track of the next ID number to be used
int ID; // the identifier for a specific object
// Member Functions
public:
YarlObject(): ID(++nextID) {}
virtual ~YarlObject() {}
int getID() const {return ID;}
};
}
#endif
这是它的实现文件。
#include "YarlObject.hpp"
namespace yarlObject
{
int YarlObject::nextID = 0;
}
我使用的是 g++,它返回三个 undefined reference to 'yarlObject::YarlObject::nextID
链接器错误。如果我将构造函数中的 ++nextID
短语更改为 nextID
,那么我只会收到一个错误,如果我将其更改为 1
,然后就可以正确链接了。我想这很简单,但是发生了什么?
I have this class that has a static member. it is also a base class for several other classes in my program. Here's its header file:
#ifndef YARL_OBJECT_HPP
#define YARL_OBJECT_HPP
namespace yarlObject
{
class YarlObject
{
// Member Variables
private:
static int nextID; // keeps track of the next ID number to be used
int ID; // the identifier for a specific object
// Member Functions
public:
YarlObject(): ID(++nextID) {}
virtual ~YarlObject() {}
int getID() const {return ID;}
};
}
#endif
and here's its implementation file.
#include "YarlObject.hpp"
namespace yarlObject
{
int YarlObject::nextID = 0;
}
I'm using g++, and it returns three undefined reference to 'yarlObject::YarlObject::nextID
linker errors. If I change the ++nextID
phrase in the constructor to just nextID
, then I only get one error, and if I change it to 1
, then it links correctly. I imagine it's something simple, but what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您链接的是生成的 .o 文件。仔细检查 makefile。
Make sure you are linking against the generated .o file. Double-check the makefile.