Sign in to follow this  

aggregate initialization list in class definition

This topic is 2395 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

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

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

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

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
Static variables must be initialized outside of the class definition, like this:


[code]#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;
}[/code]

Share this post


Link to post
Share on other sites
[quote name='greggles' timestamp='1306337815' post='4815626']
Static variables must be initialized outside of the class definition, like this:


[code]#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;
}[/code]
[/quote]

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

[code]
static const int i = 1;
[/code]

but seems like aggregates need special handling in this case..

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1306338559' post='4815630']
Integral types are an exception to this rule. Some compilers might have extensions allowing you to define static const floats (or other types) inline.
[/quote]

ah - thanks for clarification :)

Share this post


Link to post
Share on other sites

This topic is 2395 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this