【问题标题】:C++ accessing global variables/objects in a namespace with a variable/object with the same nameC++ 使用同名变量/对象访问命名空间中的全局变量/对象
【发布时间】:2012-05-15 13:20:50
【问题描述】:
#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 中的全局字符串 a 而不仅仅是本地字符串?

【问题讨论】:

    标签: c++ object namespaces global local


    【解决方案1】:

    像这样:

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

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2020-07-10
      • 2011-08-31
      • 2012-03-13
      • 2016-04-08
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多