簡體   English   中英

我可以在聲明后設置常量值嗎?

[英]Can I set constant value after declaration?

我可以在 C++ 中聲明后設置常量值嗎? 我試過:

#include <iostream>
using namespace std;

int main(){
    const int a;
    a = 56;
    cout << a;
    return 0;
}

它成功編譯,但控制台輸出為 4309678。

不,你不能。 此外,甚至不會編譯。 您需要初始化const值:

const int a = 56;

或者:

const int a{ 56 };

之后,您無法為變量分配新值,因為const 將其標記為只讀,因此無法編譯:

const int a = 56;
a = 57; // error: assignment of read-only variable 'a'

如果在 GCC 上,保持常量未初始化將產生以下錯誤:

error: uninitialized const 'a' [-fpermissive]

或者如果使用 Visual C++:

const variable "a" requires an initializer

暫無
暫無

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

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