static member of class

B

Bo Sun

hi:

please take a look at the following code fragment:

class Test{

public:
static int i;
Test() {i = 33;}
};

int main()
{

int Test::i = 40;

return 0;

}

I am wondering, as to static members, why I cannot assign it values inside
main function? does this mean that I cannot assign static member values
anywhere inside a function?

thanks,

bo
 
V

Victor Bazarov

Bo Sun said:
please take a look at the following code fragment:

class Test{

public:
static int i;
Test() {i = 33;}

Setting a static data member in a constructor is a BAD IDEA(tm).
};

int main()
{

int Test::i = 40;

The definition of a static member of a class shall appear at the SAME
namespace level as the class. Pull this definition outside the 'main'
function.
return 0;

}

I am wondering, as to static members, why I cannot assign it values inside
main function? does this mean that I cannot assign static member values
anywhere inside a function?

You're not assigning it. You're _defining_ it. And you're doing
it in a wrong place. An assignment would be

Test::i = 40;

which is fine, as long as you have it defined anywhere, otherwise
you will have an "undefined symbol" error.

Victor
 
R

Rob Williscroft

Bo Sun wrote in
hi:

please take a look at the following code fragment:

class Test{

public:
static int i;
Test() {i = 33;}
};

This is a defenition of Test::i with an initialization;

int Test::i = 40;
int main()
{

int Test::i = 40;

The obove is illegal (if it were legal it would be an defenition and
initialization not an assigment, but its just plain wrong).


This is an assignment, and it is legal.

Test::i = 40;

return 0;

}

I am wondering, as to static members, why I cannot assign it values
inside main function? does this mean that I cannot assign static
member values anywhere inside a function?

You need to seperate some concepts,

declaration :
telling the compiler that something exists.

eg: the "static int i;" in your class Test declaration
above.

defenition :
telling the comiler to create an object.

eg: int Test::i;

initialization :
giving an object its initial value (this is *not* assignment).

eg: the = 40 part of int Test::i = 40;

assignment :
giving an object a new value.

eg: Test::i = 40; in main() above.


Note that every defenition is also a declaration. Its allowable
(sometimes) for an object to be declared multiple times, but it must
have only one defenition.

HTH.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top