【问题标题】:Access static constexpr std::array without out-of-class definition在没有类外定义的情况下访问静态 constexpr std::array
【发布时间】:2014-09-21 00:34:31
【问题描述】:

我有一个定义了一些数组的类。

Points.hpp

class Points {

public:

    static constexpr std::array< double, 1 > a1 = { {
            +0.0 } };

    static constexpr std::array< double, 2 > a2 = { {
            -1.0 / std::sqrt( 3.0 ),
            +1.0 / std::sqrt( 3.0 ) } };

};

然后我的主文件使用这些数组。

main.cpp

#include "Points.hpp"

int main()
{
    // Example on how to access a point.
    auto point = Points::a2[0];

    // Do something with point.
}

当我使用 C++11 和 g++ 4.8.2 编译我的代码时,我收到以下链接器错误:

undefined reference to `Points::a2'

我试图创建一个 Points.cpp 文件,以便编译器可以从中创建一个目标文件。

Points.cpp

#include "Points.hpp"

但这并没有解决链接器错误。

我的印象是可以在类声明中将变量初始化为 C++11 中的静态 constexpr,然后按照我的方式访问它们,如这个问题所示:https://stackoverflow.com/a/24527701/1991500

我是否需要为 Points 创建一个构造函数然后实例化该类?我做错了什么?

感谢任何反馈!谢谢!

【问题讨论】:

  • 您是否将Points.hpp 的路径添加到编译器的头文件路径中?
  • Points.hpp 包含在 main.cpp 中。
  • 如果静态数据成员被 odr 使用,您需要为它们提供一个定义
  • 你是什么意思@dyp?我不应该在头文件中初始化它们吗?
  • 这不是问题。静态数据成员仅在类主体内声明(声明 => 名称存在),它在类主体外部定义(定义 => 将对象与名称关联)。类体内静态数据成员的初始化是一个奇怪的特性,它允许编译器使用变量的值(在编译时),而不必从实际对象中查询值。

标签: c++11 static constexpr stdarray one-definition-rule


【解决方案1】:

根据@dyp 的建议,我研究了静态数据成员的定义。

我的问题需要我定义 Points 类的静态成员变量。

遵循这些问题中的示例:

Is a constexpr array necessarily odr-used when subscripted?

Defining static members in C++

我需要补充:

// in some .cpp
constexpr std::array< double, 1 > Points::a1;

【讨论】:

  • 您链接到的第一个线程正在谈论内置数组,因此它与 std::array 案例无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多