簡體   English   中英

在C ++中聲明全局范圍變量const

[英]Declare a global scope variable const in c++

在C或C ++中,是否可以聲明具有全局范圍的const,但是定義是在函數內部設置的?

怎么樣做( 現場樣本

const int& MyConstValue(int x) {
    static const int myConstValue = x;
    return myConstValue;
}

int main() {
    std::cout << MyConstValue(5) << std::endl; // This is the 1st call and "wins"
    std::cout << MyConstValue(8) << std::endl;

    return 0;
}

輸出是

5
5

至少對於這甚至可以保證是線程安全的。

不,那是不可能的。 聲明必須在與定義相同的范圍內。 否則,它的名稱不相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM