【问题标题】:C++ access static constexpr arrayC++ 访问静态 constexpr 数组
【发布时间】:2020-05-01 09:11:41
【问题描述】:

我试图从另一个类中声明的数组中获取一些值。该数组具有固定长度和常量元素(我将 100% 永远不会修改其值,所以这就是我将其设为常量的原因)。

但是,当我尝试访问 main 函数中的第一个元素时,出现编译错误:

basavyr@Roberts-MacBook-Pro src % g++ -std=c++11 main.cc
Undefined symbols for architecture x86_64:
  "Vectors::vec1", referenced from:
      _main in main-c29f22.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1

如您所见,我正在使用 clang(最新版本)在 macOS Catalina 上进行编译。

[Q]:可能是什么问题? 提前谢谢你。

代码如下:

#include <iostream>

class Dimension
{
public:
    static constexpr int dim1 = 2;
    static constexpr int dim2 = 1;
};

class Vectors
{
public:
    static constexpr double vec1[2] = {4.20, 6.9};
};

int main()
{
    auto a = Vectors::vec1[0]; //I also tried initializing this to a value rather than just accessing it directly through the class like I did below
    std::cout << a << "\n";
    std::cout << Vectors::vec1[0] << "\n"; 
    return 0;
}

【问题讨论】:

  • 似乎与wandbox 上的最新clang 配合得很好。

标签: c++ class c++11 constexpr


【解决方案1】:

您正在 C++11 模式下编译;您需要在命名空间范围内为这些 constexpr static members 提供定义。请注意,从 c++17 开始,这不是必需的。

如果 const non-inline (since C++17) 静态数据成员 or a constexpr static data member (since C++11) 被 odr 使用,则仍需要命名空间范围内的定义,但它不能有初始化程序。 This definition is deprecated for constexpr data members (since C++17)

例如

class Dimension
{
public:
    static constexpr int dim1 = 2;
    static constexpr int dim2 = 1;
};

constexpr int Dimension::dim1;
constexpr int Dimension::dim2;

class Vectors
{
public:
    static constexpr double vec1[2] = {4.20, 6.9};
};

constexpr double Vectors::vec1[2];

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2019-08-02
    • 2017-04-10
    相关资源
    最近更新 更多