What is a good alternative to namespaces within cl

2019-08-05 19:16发布

The problem is C++ does not allow namespace declarations within classes.(I searched on internet and found this; if it's not true, please say it) So, what's the best way to cheat this problem?

Context: My class have an enumeration within it.

class GameCharacter {
public:
    enum MovingState {
        Running,
        Walking,
        Stopped
    };
    ...
};

OBS: This example is not real, it's totally hypothetical.

C++ defines that the enumeration names are inside the class scope, then to use these states I have to use the scope operator directly from the class name(GameCharacter::Running, for instance; or using GameCharacter::Running).

I think this is bad, because the name which belongs to the enumeration is inside the class scope; I wanted to have a scope for the RunningState enumeration. (accessing it this way: GameCharacter::MovingState::Running) My first thought, then, was to create a namespace which would define a scope for the enumeration.

class GameCharacter {
public:
    // does not compile
    namespace MovingState {
        enum State {
            Running,
            Walking,
            Stopped
        };
    };
    ...
};

But C++ forbids it. This code does not compile. (main.cpp:3:5: error: expected unqualified-id before ‘namespace’)

The reason why I'm trying to do things this way is because there is a possibility to create an second enumeration with names in same scope. Which could cause conflicting names.

class GameCharacter {
public:
    enum MovingState {
        Running,
        Walking,
        Stopped
    };
    enum DrivingState {
        Accelerating,
        Breaking,
        Stopped        // Compilation error: conflicts with previous declaration ‘GameCharacter::MovingState GameCharacter::Stopped’
    };
    ...
};

(my idea was that, in this case, the states should be referred as GameCharacter::MovingState::Stopped and GameCharacter::DrivingState::Stopped) Then, what should I do?

8条回答
甜甜的少女心
2楼-- · 2019-08-05 20:15

This sounds like a job for C++11's Strongly Typed Enumerations.

class GameCharacter {
public:
    enum class MovingState {
        Running,
        Walking,
        Stopped
    };
    ...
    void f(Movingstate m) { if (m == MovingState;:Running) ... }
};
void f() { if (mm == GameCharacter::MovingState::Running) ... }
查看更多
虎瘦雄心在
3楼-- · 2019-08-05 20:15

If you have so much in your class that you feel you need to sub-categorise it into namespaces, then your class has too many things.

You should move stuff out of it. In particular all these enums don't need to be members of a class. Why not keep them in the same namespace that the class is in?

查看更多
登录 后发表回答