Jump to content

  • Log In with Google      Sign In   
  • Create Account


aggregate initialization list in class definition


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 mancubit   Members   -  Reputation: 493

Like
0Likes
Like

Posted 25 May 2011 - 06:43 AM

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?

Sponsor:

#2 greggles   Members   -  Reputation: 347

Like
1Likes
Like

Posted 25 May 2011 - 09:36 AM

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


#3 mancubit   Members   -  Reputation: 493

Like
0Likes
Like

Posted 25 May 2011 - 09:46 AM

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..

#4 rip-off   Moderators   -  Reputation: 6874

Like
1Likes
Like

Posted 25 May 2011 - 09:49 AM

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

#5 mancubit   Members   -  Reputation: 493

Like
0Likes
Like

Posted 25 May 2011 - 11:10 AM

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 :)




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS