我对循环中的变量重新声明有疑问。
为什么在 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;
}
最佳答案
Why declaring an object in a foor loop doesn't trigger the redeclaration error?
当您在同一范围内两次(或多次)声明相同的名称时,会发生重新声明错误。看起来像
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
。
Do the object get destroyed and recreated at each iteration of the loop?
是的。将循环视为被多次调用的函数。当您进入循环/函数的主体时,其中声明的变量将被构造1,而当您到达循环/函数的末尾时,变量将被销毁。
1:它有点复杂,但我们不需要在这个答案中深入了解所有这些细节
关于c++ - 在 for 循环中重新声明对象 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537622/