【发布时间】:2018-03-28 14:45:35
【问题描述】:
我确实对循环中的变量重新声明有疑问。
为什么在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;
}
【问题讨论】:
-
在循环的每次迭代中,对象会被销毁并重新创建吗?
-
@Michele Fattoruso 这个声明集
s;没有意义,因为没有为 DataBlock 类定义比较器。 -
@VladfromMoscow 我没有将所有代码都包含在重载的运算符中,因为它不会为所问的问题添加额外的信息,而只会使代码混乱,让人们阅读更多行。我确实为该类重载了比较运算符。
标签: c++ loops variable-declaration