在for循环中重新声明对象-C ++ [英] Re-declaring object in a for loop - C++
问题描述
我确实对循环中的变量重新声明有疑问.
I do have a question on variable re-declaration in loops.
为什么在foor循环中声明对象不会触发重新声明错误?
Why declaring an object in a foor loop doesn't trigger the redeclaration error?
对象是否在循环的每次迭代中都被破坏并重新创建?
Do the object get destroyed and recreated at each iteration of the loop?
我要插入示例代码
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循环中声明对象不会触发重新声明错误?
Why declaring an object in a foor loop doesn't trigger the redeclaration error?
当您在同一范围内两次(或多次)声明同一名称时,发生重新声明错误.看起来像
A redeclaration error happens when you declare the same name twice (or more) in the same scope. That looks like
int i = 5;
int i = 6; // uh oh, you already declared i
在循环中您没有,而只有
In your loop you don't have that, you just have
loop
{
int i = 5;
}
因此无需重新声明.
您也可以拥有
int i = 5
{
int i = 6;
std::cout << i;
}
也没有重新声明错误,因为变量在不同的作用域中,并且您可以在多个作用域中使用相同的变量.在这种情况下,将打印6
,因为i
是范围内的i
.
And not have a redeclaration error as the variables are in different scopes and you can have the same variable in multiple scopes. I this case 6
would be print as that i
is the i
that is in scope.
对象是否在每次循环迭代时都被销毁并重新创建?
Do the object get destroyed and recreated at each iteration of the loop?
是的.将循环视为多次调用的函数.当您输入循环/函数的主体时,在其中声明的变量将被构造 1 ,而当您到达循环/函数的末尾时,变量将被破坏.
Yes. Think of a loop as a function that gets called multiple times. When you enter the body of a loop/function the variables declared in it get constructed1 and when you reach the end of the loop/function the variables are destroyed.
1:比这稍微复杂一点,但是我们不需要在这个答案中深入了解所有这些细节
这篇关于在for循环中重新声明对象-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!