問題描述
為什么這段 C++ 代碼在 VS2010 下無法編譯:
Why does this C++ code not compile under VS2010:
for ( int a = 0, short b = 0; a < 10; ++a, ++b ) {}
雖然這個是:
short b = 0;
for ( int a = 0; a < 10; ++a, ++b ) {}
是否禁止在for循環(huán)初始化器中聲明兩個不同類型的變量?如果是這樣,您如何解決它?
Is the declaration of two variables of different types inside the for-loop initializer prohibited? If so, how can you work around it?
推薦答案
是的,這是被禁止的.就像否則你不能在一個聲明語句中聲明不同類型的變量一樣(編輯:以@MrLister 提到的聲明符修飾符為模).您可以聲明結(jié)構(gòu)
Yes, that is prohibited. Just as otherwise you cannot declare variables of differing types in one declaration statement (edit: modulo the declarator modifiers that @MrLister mentions). You can declare structs
for (struct { int a = 0; short b = 0; } d; d.a < 10; ++d.a, ++d.b ) {}
C++03 代碼:
for (struct { int a; short b; } d = { 0, 0 }; d.a < 10; ++d.a, ++d.b ) {}
當(dāng)然,當(dāng)全部為0
時,您可以完全省略初始化器并編寫= { }
.
Of course when all are 0
, you can omit the initializers altogether and write = { }
.
這篇關(guān)于我可以在 for 循環(huán)的初始化中聲明不同類型的變量嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!