简体   繁体   中英

Static Variables Initialization Quiz

#include <stdio.h>

class C
{
   public:
          static int i;
          static int j;
};

int i = 10;
int C::i = 20;
int C::j = i + 1;

int main ()
{
    printf("%d", C::j);

    return 0;
}

What is the value of: C::j

I was reading a c++ quiz and came across the following question. I thought that the answer is 11 .

int C::j = i + 1;

Since it is accessing the non static i which is 10? So, I thought 11 should be the answer?

I compiled and ran this code through visual studio and it prints 21 . Which is confusing to me. Can someone please explain why this is happening? What am I missing?

[basic.lookup.qual]/3

In a declaration in which the declarator-id is a qualified-id, names used before the qualified-id being declared are looked up in the defining namespace scope; names following the qualified-id are looked up in the scope of the member's class or namespace.

In

int C::j = i + 1;

the declarator-id, ie, the name of the entity being declared, is C::j , which is a qualified-id . Therefore, the i following it is looked up in the scope of C , and refers to C::i .

Less technically, when you define a static data member, the initializer can be thought of as being in the scope of the class, and will find class members before globals.

This is the same rule that ensures that when a member function is defined out-of-line, names after the name of the function will be looked up in class scope and won't require explicit qualification if they refer to class members. It is more unusual seeing this being applied to definitions of static data members, but it is perfectly consistent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM