简体   繁体   English

具有全局成员歧义性的静态数据成员定义

[英]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. 当x在定义类的静态成员时既是全局变量又是类中的静态变量时,会看到如下歧义。

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 . 我在定义y遇到问题。 Why is global x not taken instead? 为什么不使用全局x WithStatic::x is taken. WithStatic::x被采用。 Why is the output of y not equal to 101 , instead of 2? 为什么y的输出不等于101而不是2?

From n4567 n4567

9.4 Static members [class.static] 9.4静态成员[class.static]

Paragraph 3: 第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; 静态成员可以直接在其类的范围内引用,也可以在从其类派生的类的范围内引用(第10条); 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. 在这种情况下,就像使用了qualified-id表达式一样引用静态成员,而qualified-id的嵌套名称说明符将引用静态成员的类范围命名为静态。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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