简体   繁体   中英

Class definition inside namespace

I have a class declaration like so:

// bar.h
namespace foo {
    class bar {
        // members both public and private
    }
}

When I define the class, I would like to do this

// bar.cpp
namespace foo::bar {
    // member definitions
}

Rather than

namespace foo {
    bar::x() {}
    bar::y() {}
    bar::z() {}
}

But I cannot. Why is this? I thought classes declared namespaces, but I must be wrong. Shouldn't the scope operator resolve the namespace scope then the class scope?

I ask because any time you have a class name of non-trivial length, it can become very repetitive to re-type the class name, especially if it has more than a few members. Maybe it's like this to make people define small class interfaces.

Why is this? I thought classes declared namespaces, but I must be wrong

You are wrong. :)

Shouldn't the scope operator resolve the namespace scope then the class scope?

It wouldn't be impossible for the language to support this, but it simply doesn't.

Probably because it might get a little confusing, and because the following would be outright lying:

class bar {
    void x();
    void y();
    void z();
};

namespace bar {
    void x() {}
    void y() {}
    void z() {}
}

Really, the analogy to this sort of "inline definitions" that you can do with namespaces, is the inline definitions of member functions:

class bar {
   void x() {}
   void y() {}
   void z() {}
};

First off, your class declaration needs a ; after it:

namespace foo 
{
    class bar 
    {
        // members both public and private
    }; // error without this
}

When you are implementing the class (non-inline), you can do it two ways:

void foo::bar::x() 
{
    // function definition
}

or

namespace foo
{
    void bar::x()
    {
        // function definition
    }
}

Note that bar is a class, not a namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM