You seem confused about how namespaces are used. Here are some things to keep in mind when working with namespaces:
- You create a namespace using the syntax
namespace identifier { /* stuff */ }
. Everything between the {
}
will be in this namespace.
- You cannot create a namespace inside a user-defined type or function.
- A namespace is an open group construct. This means you can add more stuff into this namespace later on in some other piece of code.
- Namespaces aren't declared unlike some of the other language constructs.
- If you want certain classes and/or functions inside a namespace scope, enclose it with the namespace syntax in the header of where it's defined. Modules using those classes will see the namespace when the headers get
#include
'd.
For example, in your Entity.h
you might do:
// Entity.h
#pragma once
namespace EntityModule{
class Entity
{
public:
Entity();
~Entity();
// more Entity stuff
};
struct EntityFactory
{
static Entity* Create(int entity_id);
};
}
inside your main.cpp
you access it like this:
#include "Entity.h"
int main()
{
EntityModule::Entity *e = EntityModule::EntityFactory::Create(42);
}
If you also want Player
to be inside this namespace then just surround that with namespace EntityModule
too:
// Player.h
#pragma once
#include "Entity.h"
namespace EntityModule{
class Player : public Entity
{
// stuff stuff stuff
};
}
This works because of point #3 above.
If for some reason you feel you need to create a namespace inside a class, you can simulate this to an extent using nested classes:
class Entity
{
public:
struct InnerEntity
{
static void inner_stuff();
static int more_inner_stuff;
private:
InnerEntity();
InnerEntity(const InnerEntity &);
};
// stuff stuff stuff
};
Some important differences and caveats doing it this way though:
- Everything is qualified with
static
to indicate there's no specific instance associated.
- Can be passed as a template parameter.
- Requires a
;
at the end.
- You can't create a convenient shorthand with
abusing namespace Entity::InnerEntity;
. But perhaps this is a good thing.
- Unlike namespaces,
class
and struct
are closed constructs. That means you cannot extend what members it contains once defined. Doing so will cause a multiple definition error.