简体   繁体   中英

Static data member definition with global member ambiguity

When x is a global variable as well as a static variable in class while defining the static member of class, ambiguity as below is seen.

ambiguity.cpp
using namespace std;

int z = 100;

int x = 100;

class WithStatic {

    static int x;
    static int y;
    static int a;

    public:

        void print() const {
            cout << "WithStatic::x = " << x << endl;
            cout << "WithStatic::y = " << y << endl;
            cout << "WithStatic::a = " << a << endl;
        }
};

int WithStatic::x = 1;
int WithStatic::y = x + 1;
int WithStatic::a= z+1;

int main() {
    WithStatic ws;
    ws.print();
}

Output:

WithStatic::x = 1

WithStatic::y = 2

WithStatic::a = 101

I have a problem at defining y . Why is global x not taken instead? WithStatic::x is taken. Why is the output of y not equal to 101 , instead of 2?

From n4567

9.4 Static members [class.static]

Paragraph 3:

A static member may be referred to directly in the scope of its class or in the scope of a class derived (Clause 10) from its class; in this case, the static member is referred to as if a qualified-id expression was used, with the nested-name-specifier of the qualified-id naming the class scope from which the static member is referenced.

// Example:
int g();
struct X
{
    static int g();
};
struct Y : X
{
    static int i;
};
int Y::i = g(); // equivalent to Y::g();

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