【问题标题】:class public function refer to private array类公共函数引用私有数组
【发布时间】:2020-12-08 06:41:24
【问题描述】:

我正在尝试构建一个具有公共函数的类,该类可以根据索引访问私有数组成员。

#include <iostream>
#include <array>

class foo{
public:
    int get_value_from_table(int row_number){
        return table[row_number];
    }

private:
    constexpr static std::array<int, 2> table = {1,2};
    //void initialize_table();
};

int main() {
    foo a;
    int b = a.get_value_from_table(1);
    std::cout << b << std::endl;
    return 0;
}

构建代码时出现undefined symbol foo::table 错误。如何修复错误?

Undefined symbols for architecture x86_64:
  "foo::table", referenced from:
      foo::get_value_from_table(int) 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)

【问题讨论】:

    标签: c++ class


    【解决方案1】:

    发布的代码应该可以在 C++17 及更高版本中正常工作。

    在 C++17 之前,static constexpr 成员还需要在类声明之外进行定义。

    constexpr std::array<int, 2> foo::table; // still allowed but no longer required in C++17
    

    相关见解和指点可以在constexpr static member before/after C++17下找到。

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2013-03-18
      • 2017-11-29
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多