aggregate initialization list in class definition

Started by
3 comments, last by mancubit 12 years, 11 months ago
Maybe someone can help me with this: i want to define a constant array using a aggregate initialization list within the class definition in C++

normally an aggregation list can be used like this


const int i[] = { 1, 2, 3, 4 };


in a class definition you have to use the static keyword - but the following does not work


static const int i[] = { 1, 2, 3, 4 };


i am getting errors like "error C2059: syntax error : '{'", "error C2334: unexpected token(s) preceding '{'; skipping apparent function body"
for some reason the compiler thinks this aggregate is actually a function.

how can i do this correctly and why is it not working?
Advertisement
Static variables must be initialized outside of the class definition, like this:


#include <iostream>
using namespace std;

class A
{
public:
static const int i[];
};

const int A::i[] = {1, 2, 3, 4};

int main()
{
cout << A::i[0] << endl;
return 0;
}

Static variables must be initialized outside of the class definition, like this:


#include <iostream>
using namespace std;

class A
{
public:
static const int i[];
};

const int A::i[] = {1, 2, 3, 4};

int main()
{
cout << A::i[0] << endl;
return 0;
}



thank you!
i was just wondering as this works within the class definition


static const int i = 1;


but seems like aggregates need special handling in this case..
Integral types are an exception to this rule. Some compilers might have extensions allowing you to define static const floats (or other types) inline.

Integral types are an exception to this rule. Some compilers might have extensions allowing you to define static const floats (or other types) inline.


ah - thanks for clarification :)

This topic is closed to new replies.

Advertisement