Access static constexpr std::array without out-of-class definition

懵懂的女人 提交于 2019-12-11 02:38:24

问题


I have a class that defines some arrays.

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

};

My main file then uses these arrays.

main.cpp

#include "Points.hpp"

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

    // Do something with point.
}

When I compile my code, using C++11 and g++ 4.8.2, I get the following linker error:

undefined reference to `Points::a2'

I attempted to create a Points.cpp file so that the compiler can create an object file from it.

Points.cpp

#include "Points.hpp"

But that did not fix the linker error.

I was under the impression that it was possible to initialize variables as static constexpr in C++11 in the class declaration, and then access them the way I'm doing it, as shown in this question: https://stackoverflow.com/a/24527701/1991500

Do I need to make a constructor for Points and then instantiate the class? What am I doing wrong?

Any feedback is appreciated! Thanks!


回答1:


As per @dyp suggestion, I looked into the definition of static data members.

My problem requires me to define the static member variables of my Points class.

Following the examples in these questions:

Is a constexpr array necessarily odr-used when subscripted?

and

Defining static members in C++

I need to add:

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


来源:https://stackoverflow.com/questions/25954621/access-static-constexpr-stdarray-without-out-of-class-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!