initializing arrays

Pages: 12
:)

Now i want to know what was the problem with your code...

It dont make any sense. It is a syntax error, so it cant be something with the placement in a class or someting, but on the other hand, exactly the same syntax does work in a simple program...
yeah i know
my lecturer couldnt even figure this shit out man

im gonna try it on another compiler tomorrow
ill let you know how it goes man
Yes, if you figured someting out, please tell me :)
Ok, the problem is that you can't initialize variables declared inside a class this way.

This does not work:

1
2
3
4
class Foo {
   public:
      int x = 5;
};


Hence your array assignment doesn't work either.

This works:

1
2
3
4
class Foo {
   public:
      static int x = 5;
};


because of the static declaration. But this is probably not what you want.

What you want is to initialize your array inside the constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Foo {
   public:
       // Constructor:
       Foo();

       char alphabet[26];
};

And then in .cpp file:

Foo::Foo() {
    for( int idx = 0; idx < sizeof( alphabet ); ++idx )
       alphabet[ idx ] = 'a' + idx;
}

Great, finally somebody who understand it! :)


Some questions:
-Wy cant you declare a variable inside a class?
-Wy gave the compiler a syntax "{" error, if the problem was with the location?
-How does a static declaration works?
1. You can. Declaration and initialization are two different things. int x; declares a variable named x of type int. x = 5; initializes or assigns x the value 5. int x = 5; both declares and initializes x. Your code was declaring and initializing.

2. That has to do with the way parsing works. The compiler doesn't know what you were trying to do. That is, it does not know the semantics of your code. But the compiler does know the syntax of C++, and '{' is not allowed there.

3. static has multiple meanings. Inside a class, as in my example above, it means that there is only one x, no matter how many instances of Foo there are. It also means that you don't have to declare an object of type Foo in order for the variable Foo::x to exist.

oke, thanks, i get it now
initializing arrays.... In class.....
Хорошая шутка. =) (Nice joke)
Best way (why not?)
1
2
3
4
5
class ClassName
{ ...
    static int days[13];
...};
int Date::days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

Last edited on
cheers jsmith
it worked perfectly
Topic archived. No new replies allowed.
Pages: 12