Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a class within a namespace

Is there a more succinct way to define a class in a namespace than this:

namespace ns { class A {}; }

I was hoping something like class ns::A {}; would work, but alas not.


1 Answers

You're close, you can forward declare the class in the namespace and then define it outside if you want:

namespace ns {
    class A; // just tell the compiler to expect a class def
}

class ns::A {
    // define here
};

What you cannot do is define the class in the namespace without members and then define the class again outside of the namespace. That violates the One Definition Rule (or somesuch nonsense).

like image 65
D.Shawley Avatar answered Sep 07 '25 20:09

D.Shawley