对静态成员变量的未定义引用

发布于 2024-09-02 17:47:39 字数 881 浏览 0 评论 0原文

我有一个有静态成员的类。它也是我的程序中其他几个类的基类。这是它的头文件:

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

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

发布评论

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

评论(1

递刀给你 2024-09-09 17:47:39

确保您链接的是生成的 .o 文件。仔细检查 makefile。

Make sure you are linking against the generated .o file. Double-check the makefile.

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