[英]Re-declaring object in a for loop - C++
我確實對循環中的變量重新聲明有疑問。
為什么在foor循環中聲明對象不會觸發重新聲明錯誤?
在循環的每次迭代中,對象是否都被銷毀並重新創建?
我正在插入示例代碼
class DataBlock {
int id;
string data;
public:
DataBlock(int tid=0,const string &tdata=""){
id=tid;
data=tdata;
}
}
int main(int argc, char *argv[]){
ifstream file;
int temp_id; //temporary hold the the id read from the file
string temp_data; //temporary hold the data read from the file
set <DataBlock> s;
//check for command line input here
file.open(argv[1]);
//check for file open here
file >> temp_id >> temp_data;
while (!file.eof()){
DataBlock x(temp_id,temp_data); //Legit, But how's the workflow?
s.insert(x);
file >> temp_id >> temp_data;
}
file.close();
return 0;
}
為什么在foor循環中聲明對象不會觸發重新聲明錯誤?
當您在同一范圍內兩次(或多次)聲明同一名稱時,會發生重新聲明錯誤。 看起來像
int i = 5;
int i = 6; // uh oh, you already declared i
在你的循環中你沒有那個,你只有
loop
{
int i = 5;
}
因此,無需重新聲明。
你也可以
int i = 5
{
int i = 6;
std::cout << i;
}
並且沒有重新聲明錯誤,因為變量在不同的作用域中,並且您可以在多個作用域中使用相同的變量。 我將這種情況6
打印出來,因為i
是范圍內的i
。
在循環的每次迭代中,對象是否都被銷毀並重新創建?
是。 可以將循環視為多次調用的函數。 當您輸入循環/函數的主體時,在其中聲明的變量將被構造為1,而當您到達循環/函數的末尾時,變量將被銷毀。
1:比那稍微復雜一點,但是我們不需要深入研究這個答案中的所有細節
為什么在foor循環中聲明對象不會觸發重新聲明錯誤?
不,不是的。
每次循環for循環時,都會輸入一個新作用域,並破壞在前一個對象中創建的對象,並釋放其存儲分配。
for (int i=0 ; i<2 ; ++i) {
MyClass c;
}
就像:
{
int i=0;
{
MyClass c; // c(0)
} // c destructed, storage allocation freed
++i;
{
MyClass c; // c(1)
} // c destructed, storage allocation freed
++i;
}
c(0)
和c(1)
確實具有相同的名稱,但是作用域沒有重疊。 一切順利。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.