开发者

C++: Namespace syntax question

开发者 https://www.devze.com 2023-01-31 17:28 出处:网络
namespace Stuff { class Sprite { }; class Circle : Stuff::Sprite { }; } Will this work, or will this look for St开发者_如何转开发uff::Stuff::Sprite?
namespace Stuff
{
    class Sprite
    {
    };

    class Circle : Stuff::Sprite
    {
    };
}

Will this work, or will this look for St开发者_如何转开发uff::Stuff::Sprite?

edit: forgot some semicolons.

edit 2: I'm accepting @Omnifarious' answer because once he edited it with @Vlad's help, it was the most complete answer. thanks also to @Vlad.


This will work unless there is a namespace Stuff::Stuff visible at definition point.

Example:

namespace Stuff
{
    namespace Stuff
    {
    }

    class Sprite
    {
    };

    class Circle : public Stuff::Sprite // compile error,
    {                                   // looks for Stuff::Stuff::Sprite
    };
}

Without the inner namespace Stuff it would work.


It will work if you put in the ; after the class definitions. But it will not work in quite the way you expect. First, it tries to figure out what namespace you're talking about. First it will looks for ::Stuff::Stuff, and when it doesn't find it, it then looks for the namespace ::Stuff. It finds that namespace, so it then looks in that namespace for Sprite and finds your class.

If you have an unanchored namespace, it looks for that namespace path in the current namespace, then in the enclosing namespace, then in the enclosing enclosing namespace... etc... until it gets to the top level namespace.

See this question of mine:

  • Why does everybody use unanchored namespace declarations (i.e. std:: not ::std::)?

In my opinion, people ought to be a lot more careful than they are about referring to namespaces. Hardly anybody ever uses a root anchored namespace specification, even when they should be because they really do mean a specific absolute namespace and not a name relative to the current namespace.

Here are a couple of interesting cases:

 1 namespace Bar {
 2
 3 class A {
 4 };
 5
 6 } // end namespace ::Bar
 7
 8 namespace Foo {
 9
10 class A {
11 };
12
13 Foo::A joe; // Refers to the A declared on line 10
14
15 namespace Foo {
16 }
17
18 Foo::A fred; // Error, finds ::Foo::Foo and doesn't find A there.
19 ::Foo::A fred; // Works and refers to the A declared on line 10
20
21 Bar::A barney; // Works, and refers to the A declared on line 3
22
23 namespace Bar {
24
25 class A {
26 };
27
28 } // end namespace ::Foo::Bar
29
30 Bar::A wilma; // Works, and refers to the A declared on line 25
31 ::Bar::A betty; // Also works, and refers to the A declared on line 3
32 ::Foo::Bar::A dino; // Also works, and refers to the A declared on line 25
33 } // end namespace ::Foo
0

精彩评论

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