Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

C++ namespaces and defining classes in separate files

I want to make a namespace that will contain several classes as part of a "package".

Do I have to declare all of the classes within the namespace?

For example, if I have a "2dEngine.h" which defines the 2dEngine namespace, do I have to declare all of the individual classes within that header file? Or can I still separate them into separate header (.h) files and have them be part of the namespace?

Pseudo example:

TwoEngine.h

namespace TwoEngine
{
    class Canvas
    {
        // Define all of Canvas here
    };

    class Primitive
    {
        // Define all of Primitive here
    };
}

Instead of doing that, I want to have Canvas and Primitive be their own .h files and just somehow state that they are part of that namespace.

Sorry, I'm still pretty new to this.

question from:https://stackoverflow.com/questions/4093407/c-namespaces-and-defining-classes-in-separate-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you can split the namespace into multiple blocks (and hence files). Your classes will belong to the same namespace as long as they are declared in the namespace block with the same name.

// Canvas.h
namespace TwoEngine
{
    class Canvas
    {
        // Define all of Canvas here
    };
}

// Primitive.h
namespace TwoEngine
{
    class Primitive
    {
        // Define all of Primitive here
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...