本文介紹了C++中的變量初始化的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我的理解是int
變量會自動初始化為0
;然而,事實并非如此.下面的代碼打印一個隨機值.
My understanding is that an int
variable will be initialized to 0
automatically; however, it is not. The code below prints a random value.
int main ()
{
int a[10];
int i;
cout << i << endl;
for(int i = 0; i < 10; i++)
cout << a[i] << " ";
return 0;
}
- 哪些規則(如果有)適用于初始化?
- 具體來說,在什么條件下變量會自動初始化?
- 它是一個類/結構實例,其中默認構造函數初始化所有原始類型;像
MyClass 實例;
- 您使用數組初始值設定項語法,例如
int a[10] = {}
(全部歸零)或int a[10] = {1,2};
(除前兩項外全部歸零:a[0] == 1
和a[1] == 2
) - 同樣適用于非聚合類/結構,例如MyClass 實例 = {};(關于這方面的更多信息可以在 這里)
- 這是一個全局/外部變量
- 變量被定義為
static
(無論是在函數內還是在全局/命名空間范圍內) - 感謝 Jerry - it's a class/struct instance in which the default constructor initializes all primitive types; like
MyClass instance;
- you use array initializer syntax, e.g.
int a[10] = {}
(all zeroed) orint a[10] = {1,2};
(all zeroed except the first two items:a[0] == 1
anda[1] == 2
) - same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here)
- it's a global/extern variable
- the variable is defined
static
(no matter if inside a function or in global/namespace scope) - thanks Jerry
推薦答案
如果
永遠不要相信一個普通類型(int、long、...)的變量會被自動初始化!它可能會發生在像 C# 這樣的語言中,但不會發生在 C &C++.
Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.
這篇關于C++中的變量初始化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!