1

The following 3 code blocks are the main.cpp, static_class_array.cpp, and static_class_array.h respectively. I'm getting the following error:

static_class_array.cpp||In constructor 'static_array_class::static_array_class()':|
static_class_array.cpp|5|error: cannot convert '<brace-enclosed initializer list>' to 'int' in assignment|
||=== Build finished: 1 errors, 0 warnings ===|


#include "static_class_array.h"

int main()
{
    static_array_class* array_class;

    array_class = new static_array_class();

    delete array_class;

    return 0;
}


#include "static_class_array.h"

static_array_class::static_array_class()
{
    static_array_class::array[3] = {0,1,2};
}
static_array_class::~static_array_class(){}



#ifndef STATIC_CLASS_ARRAY_H
#define STATIC_CLASS_ARRAY_H

class static_array_class
{
    private:

        static int array[3];

    public:

    static_array_class();
    ~static_array_class();
};
#endif
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
pandoragami
  • 5,387
  • 15
  • 68
  • 116

2 Answers2

2

They are not the same type;

Your class is a class which includes a an array -- they other is just an array.

With a static definition of a class member you need to declare the actual instance outside the class, just like with any other static,

int static_array_class::array[3] = {0,1,2}; // note this line is outside the constructor

static_array_class::static_array_class()
{
}
static_array_class::~static_array_class(){}
Soren
  • 14,402
  • 4
  • 41
  • 67
  • Sure is possible with coding -- you just need a bit more -- static members of a class are initialized not in the constrictor but outside the class, since they are not actually part-taking in the constrction/deconstrction -- just can almost consider them just a part of the name space rather than the class. – Soren Aug 22 '11 at 00:09
  • Also see this Q&A: http://stackoverflow.com/questions/185844/initializing-private-static-members – Soren Aug 22 '11 at 00:14
  • I tried that and then it tells me \static_class_array\static_class_array.cpp|6|undefined reference to `static_array_class::array'| – pandoragami Aug 22 '11 at 00:30
  • Updated the answer, you need to move the initialization outside the constructor and declare the actual static member instance – Soren Aug 22 '11 at 00:41
2

I think that what you want in the implementation file is:

    static_array_class::static_array_class()
    {
    }
    static_array_class::~static_array_class(){}

    int static_array_class::array[3] = {0,1,2};

Explanation of error message

"cannot convert 'brace-enclosed initializer list' to 'int' in assignment"

in submitted code.

This is because the code:

static_array_class::array[3] = {0,1,2};

is interpreted as meaning that {0,1,2} should be assigned to element 3 in the array. Element 3 is of type int, (and incidentally not allocated being the fourth element), so this is like:

int i = 0;
i = {0,1,2};

Hence the error message.

Keith
  • 6,756
  • 19
  • 23