在for循环中重新声明对象 - C ++

时间:2018-03-28 14:45:35

标签: c++ loops variable-declaration

我对循环中的变量重新声明有疑问。

为什么在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;
}

2 个答案:

答案 0 :(得分:4)

  

为什么在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:它有点复杂,但我们不需要在这个答案中介绍所有这些细节

答案 1 :(得分:2)

  

为什么在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)确实共享相同的名称,但在范围内没有重叠。一切都很好。