Jump to content
  • Advertisement
Sign in to follow this  
mancubit

aggregate initialization list in class definition

This topic is 2615 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites

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

Share this post


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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!