首页 > C++变量重复定义

C++变量重复定义

代码1:

int main()
{
   {const std::string s="a string";
    std::cout<<s<<std::endl;}
   {
    const std::string s="another string";
    std::cout<<s<<std::endl;
   }
}

代码2:

int main()
{
   {const std::string s="a string";
    std::cout<<s<<std::endl;
   {
    const std::string s="another string";
    std::cout<<s<<std::endl;}
   }
}

代码3:

int main()
{
   {const std::string s="a string";
    std::cout<<s<<std::endl;

   {
    const std::string s="another string";
    std::cout<<s<<std::endl;};
   }
}

以上三段代码都是可运行的正确代码,代码1我知道是因为,在每个}到来时都会destroy s这个变量,但是代码2在第二个s定义的时候,第一个s并未destroy,为什么编译时没有报冲突呢?代码3为什么加了个“多余”的分号以后仍然能正常运行呢?


2,3的代码中,两个s在不同的作用域,被嵌套的作用域会覆盖父作用域中的同名变量。


代码2,希望题主好好看看 C++ Primer 5th 的 2.2.4. Scope of a Name,里面讲解了这部分内容。

两个作用域,两个对象,我们管他们分别叫:括号外的s,括号内的s。这样的定义完全合法,他们的块作用域不同而已。括号内的cout语句优先选择local definition,即括号内的s,所以你依旧可以打印出“another string”。

代码3,就是空语句,希望题主好好看看 C++ Primer 5th 的 5.1. Simple Statements “Null Statements”

while (cin >> s && s != sought)    
    ; // null statement 

这样写是非常合法的,而且还是非常有用的。

【热门文章】
【热门文章】