开发者

C++: Visibility of parent namespace to child namespace

If you have ns2 as a child namespace of ns1, and you use ns1 classes inside a header for an ns2 class, do you need to explicitly decalre it as you would when ns1 & ns2 are unrelated?

e.g

button.h

namespace ns1
{
 class Button
 {
  ...
 };
}

dialog.h

include "button.h"
namespace ns1
{
 namespace ns2
 {
  cl开发者_开发知识库ass TestDialog
  {
   Button *pButton;
  };
 }
}

Should that be right? It seems I have to change dialog.h to be:

namespace ns1
{
 ----->class Button;
 namespace ns2
 {

But I'm not quite sure why. Do namespaces not inherit? If I don't make this change, I get linker errors about "unresolved symbol ns1::ns2:Button::...".


All functions, classes (types), vars, etc. declared in a namespace will be available (without prefix) in all sub namepaces and so on. So when namespace n2 is defined in n1 all code in n2 can use n1 code without prefix.


Your code works fine for me in gcc 4.4.5 without the additional declaration of Button. You are missing a # from the include line, but I suppose that is just a transcription error. Are you sure that this is the part of your code that is causing the problem?

EDIT: In your actual code, you are probably not using the names ns1 and ns2 - maybe you have misspelled the namespaces somewhere?


You are missing a # sign, recompile with #include and you should be fine. The problem is when you don't include, you never actually declared the class in the other file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜