Q Stollen
Q Stollen

Reputation: 41

Initialize class variable float array in C++

I'm trying to initialize a class variable array. As I understand normal class variable initialization works like this:

class test
{
public:
    static const float f;
};

However, as an array, it suddenly doesnt work:

class test
{
public:
    static const float f[2];
};
//const float test::f = { 1 ,2};

The whole code should work, but I commented out the line 6. In line 4, it still threw

Error LNK2001 unresolved external symbol "public: static float const * const test::f"

I tried pointers and dynamic allocation, both of which didn't work either. How can I fix this error, and is there something wrong with line 6?

Upvotes: 0

Views: 1943

Answers (2)

user1180790
user1180790

Reputation:

Explanation

static test::f means that f is not bound to test class instances. In other words, there is only one, single f like if test was namespace, not class. There is only one and exactly one f.

Note

Also, You've forgot to add size of f array which must be given at compile time. You can also always use decltype specifier that will automagically provide correct type of member for you.

Basic example

#include <iostream>

class test
{
public:
    static const float f[2];
};

decltype(test::f) test::f = {1, 2};

int main(){
    // Outputs: 1, 2
    std::cout << test::f[0] << ", " << test::f[1];
}

Modern example

More modern solution would use std::array, initializer list, auto placeholder type specifier and constexpr specifier. In that case, you don't need to provide array size at all.

#include <iostream>
#include <array>

class test
{
public:
    static constexpr auto f = std::array {1.f, 2.f};
};

int main(){
    // Outputs: 1, 2
    std::cout << test::f[0] << ", " << test::f[1];
}

Upvotes: 1

Chi
Chi

Reputation: 322

As @NathanOliver was saying, you can add the size to your initialization outside of the class:

class test                                                                   
{                                                                            
public:                                                                      
    static const float f[2];                                                 
};                                                                           
...                                                                          
const float test::f[2] = {1, 2};

Alternatively, you can also use constexpr and declare the array within the class itself:

class test                                                                  
{                                                                           
public:                                                                     
    static constexpr float f[2] = {1, 2};                                   
};

Upvotes: 1

Related Questions