Classes and namespaces sharing the same name in C++

南笙酒味 提交于 2019-12-17 21:30:07

问题


Let's say I have a class called 'foo' in namespace "abc"...

namespace abc {
     class foo {
         int a;
         int b;
     };
}

...and then say I have another class called "abc" in a different namespace

#include "foo.h"

namespace foo {
    class abc {
        abc::a = 10;
    };
}

abc::a would not be a defined type, because it would be searching class abc, not namespace abc. How would I go about properlly referencing an object in another namespace, wherein that other namespace had the same name as the class I'm in?


回答1:


You can use ::abc::xx, that is, identify the variable or type as its absolute namespace path. If you don't specify an absolute name, relative names start going upwards in the including namespaces/classes.




回答2:


You can use a prefix :: to denote starting from the global namespace, so in your case ::abc would denote the abc namespace from your first code snippet.




回答3:


You can specify a fully qualified name starting from :: which defines the global namespace, e.g.:

namespace abc {
   class foo {
       int a;
       int b;
   };
}

namespace foo {
  class abc {
      ::abc::foo a; // Changed from 'abc::a = 10;' since it doesn't compile
  };
}


来源:https://stackoverflow.com/questions/4070915/classes-and-namespaces-sharing-the-same-name-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!