【问题标题】:Undefined reference to static member variable fixed by adding 0通过添加 0 修复对静态成员变量的未定义引用
【发布时间】:2019-11-02 05:53:38
【问题描述】:

我希望了解 g++ 在尝试链接我的代码时产生的以下错误。有问题的链接错误如下

ClassA.cpp:17: undefined reference to `ClassA::xOffset'
ClassA.cpp:17: undefined reference to `ClassA::yOffset'

这个错误来自这一行

ClassA::ClassA(int width, int height) : m_width(width - 2 * xOffset), 
                                        m_height(height - 2 * yOffset),
                   ---> error here      m_classB(50, 300,std::make_tuple(xOffset + m_width, xOffset), std::make_tuple(yOffset + m_height, yOffset))

该错误与创建元组和在每个 make_tuple 调用的第二个条目中引用 xOffset 和 yOffset 有关。

查看关于 SO 的其他问题,我注意到人们在不分配静态成员变量时遇到了同样的问题。但是,这是我的班级定义。

class ClassA {
    public:
        ClassA(int width, int height);
        .....

    private:
        static const int xOffset = 150;
        static const int yOffset = 300;

        int m_width;
        int m_height;

        ClassB m_classB;
        ....
};

xOffset 和 yOffset 都被初始化了。

奇怪的是,在解决了错误之后,我可以通过将初始化行更改为 this 来消除链接错误

ClassA::ClassA(int width, int height) : m_width(width - 2 * xOffset), 
                                        m_height(height - 2 * yOffset),
                                        m_classB(50, 300,std::make_tuple(xOffset + m_width, xOffset + 0), std::make_tuple(yOffset + m_height, yOffset + 0))

唯一的变化是将 0 添加到 xOffset 和 yOffset。这消除了链接错误并允许我编译和运行我的代码。

我的问题是为什么添加 + 0 会修复链接错误,为什么我可以在创建 m_width 和 m_height 时在初始化列表中引用静态变量 xOffset 和 yOffset 但在初始化列表的下一项中再次这样做会导致链接器错误?

【问题讨论】:

    标签: c++ class static g++


    【解决方案1】:

    我猜你的 cpp 文件需要添加:

    const int ClassA::xOffset;
    const int ClassA::yOffset;
    

    【讨论】:

    • 我能够修复它,但我希望了解为什么会发生此错误:)
    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2021-12-13
    相关资源
    最近更新 更多