C++ 访问静态 constexpr 数组

Rob*_*aru 2 c++ class constexpr c++11

我试图从另一个类中声明的数组中获取一些值。该数组具有固定长度和常量元素(我将 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
Run Code Online (Sandbox Code Playgroud)

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

[问]:可能是什么问题?先感谢您。

这是代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 8

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

如果odr 使用了 constnon-inline (since C++17)静态数据成员or a constexpr static data member (since C++11),则仍然需要命名空间范围内的定义,但它不能有初始化程序。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];
Run Code Online (Sandbox Code Playgroud)