c++ 靜態變數初始化測驗
#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
我正在讀一個c測驗,遇到以下問題.我以為答案是11.
int C :: j = i 1;
因為它正在訪問非靜態i是10?那麼,我以為11應該是答案?
我編譯並執行這個程式碼通過視覺工作室,它列印21.這是令我困惑的.有人可以解釋為什麼會發生這種情況嗎?我失蹤了什麼
[basic.lookup.qual] / 3
In a declaration in which thedeclarator-id is aqualified-id, names used before thequalified-id being declared
are looked up in the defining namespace scope; names following thequalified-id are looked up in the scope
of the member’s class or namespace.
在
int C::j = i + 1;
declarator-id,即正在宣告的實體的名稱是C :: j,它是一個限定id.因此,我跟隨它在C的範圍內查詢,並且指C :: i.
在技術上,在定義靜態資料成員時,初始化器可以被認為是在類的範圍內,並且在全域性變數之前會發現類成員.
這是一個相同的規則,可以確保當一個成員函式被定義為行之外時,函式名稱之後的名稱將在類範圍內查詢,並且如果它們引用類成員則不需要明確的限定.更不尋常的是,這被應用於靜態資料成員的定義,但它是完全一致的.
http://stackoverflow.com/questions/32362904/static-variables-initialization-quiz