簡體   English   中英

具有全局成員歧義性的靜態數據成員定義

[英]Static data member definition with global member ambiguity

當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();
}

輸出:

WithStatic::x = 1

WithStatic::y = 2

WithStatic::a = 101

我在定義y遇到問題。 為什么不使用全局x WithStatic::x被采用。 為什么y的輸出不等於101而不是2?

n4567

9.4靜態成員[class.static]

第3段:

靜態成員可以直接在其類的范圍內引用,也可以在從其類派生的類的范圍內引用(第10條); 在這種情況下,就像使用了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