标签:variable-declaration c loops
我确实对循环中的变量重新声明有疑问.
为什么在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.
Do the object get destroyed and recreated at each iteration of the loop?
是.可以将循环视为多次调用的函数.当您输入循环/函数的主体时,在其中声明的变量将被构造1,而当您到达循环/函数的末尾时,变量将被销毁.
1:比那稍微复杂一点,但是我们不需要深入研究这个答案中的所有细节
标签:variable-declaration,c,loops 来源: https://codeday.me/bug/20191013/1906007.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。