加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C访问具有相同名称的变量/对象的命名空间中的全局变量/对象

发布时间:2020-12-16 06:04:09 所属栏目:百科 来源:网络整理
导读:#include iostream#include stringusing namespace std;string a;namespace myNamespace{ string a; void output() { cout a endl; }}int main(){ a = "Namespaces,meh."; myNamespace::a = "Namespaces are great!"; myNamespace::output();} 结果是“命名
#include <iostream>
#include <string>
using namespace std;

string a;

namespace myNamespace
{
    string a;
    void output()
    {
        cout << a << endl;
    }
}

int main()
{
    a = "Namespaces,meh.";
    myNamespace::a = "Namespaces are great!";
    myNamespace::output();
}

结果是“命名空间很棒!”.那么有什么办法可以访问命名空间myNamespace中的全局字符串,而不仅仅是本地的吗?

解决方法

喜欢这个:
void output()
{
    cout << ::a << endl;  //using :: = the global namespace 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读