variables - C++变量重复定义
大家讲道理
大家讲道理 2017-04-17 11:37:04
[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)
伊谢尔伦

代码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 

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

迷茫

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号