【问题标题】:Undefined symbols when referencing static variable inside class [duplicate]引用类内的静态变量时未定义的符号[重复]
【发布时间】:2018-11-27 22:17:20
【问题描述】:

以下代码无法编译,我不太确定我是否理解原因:

class A {
public:
    virtual ~A() {}
};

class B : public A {
public:
    virtual ~B() {}
    static B* I() { return &i_; }

protected:
    static B i_;
    explicit B() {}
};

int main() {
    A* a = B::I();
    (void)a;
    return 0;
}

Undefined symbols for architecture x86_64:
  "B::i_", referenced from:
      B::I() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

I() 方法应该可以访问该符号,但事实并非如此。

Apple LLVM 版本 9.1.0 (clang-902.0.39.2)

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    将此添加到您的 .cpp 的全局范围以定义 i_ 静态成员:

    B B::i_;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      相关资源
      最近更新 更多