gpt4 book ai didi

C++ 访问静态 constexpr 数组

转载 作者:行者123 更新时间:2023-12-01 19:33:55 45 4
gpt4 key购买 nike

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

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

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

这是代码:

#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;
}

最佳答案

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

If a const non-inline (since C++17) static data member or a constexpr static data member (since C++11) is odr-used, a definition at namespace scope is still required, but it cannot have an initializer. 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];

关于C++ 访问静态 constexpr 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737234/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com