On Wed, 25 Feb 2004 22:53:06 +0800, "Qin Chen" <wi*******@etang.com>
wrote:
Hi, all!
I need some experieced coder to explain what the following code will
produce, thank you!
#inlcude <iostream>
#include <iostream>
using namespace std;
class WithStatic{
static int x;
static int y;
public:
void print(void);
};
void WithStatic::print(void)
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}
int x = 100;
int WithStatic::y = x + 1;
int WithStatic::x = 10;
int main()
{
WithStatic ws;
ws.print();
}
That code must produce:
x = 10
y = 11
This is because the initializer for a static variable is in the scope
of the class. Members of the class can be used without qualification,
and hide names from enclosing scopes to the initialization, so the "x
+ 1" refers to "WithStatic::x + 1".
Because WithStatic::x is statically initialized but WithStatic::y is
dynamically initialized (with the non-constant expression "x + 1"),
the fact that it appears before the x initialization doesn't matter -
it will still get the correct value of WithStatic::x. This is similar
to:
extern int i;
int j = i + 1; //dynamic initialization happens later
int i = 10; //static initialization happens first
Here j == 11.
Tom
--
C++ FAQ:
http://www.parashift.com/c++-faq-lite/
C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html