开发者

Accessing an enum in a namespace

开发者 https://www.devze.com 2023-01-06 20:11 出处:网络
In a header I have a setup like this namespace NS { typedef enum { GOOD, BAD, UGLY }enum_thing; class Thing {

In a header I have a setup like this

namespace NS {
    typedef enum { GOOD, BAD, UGLY }enum_thing;
    class Thing {
        void thing(enum_thing elem);
    }
}

and of course another cpp file that goes along with that header. Then I have a thread cpp file that contains main(). In this cpp file I use that en开发者_如何学JAVAum to pass to the method thing().

using namespace NS;
int main() {
    Thing t();
    t.thing(BAD);
}

and of course I get other errors from G++ saying BAD was not declared. Any help on how I could overcome this error?


After correcting numerous little syntax errors in the sample code, it compiles just fine for me. Check that you've spelled the names correctly. Can you access the enum as NS::BAD? Perhaps you haven't included the correct header? Make sure you have #include "FileWithEnum.h" at the top.

namespace NS {
    typedef enum { GOOD, BAD, UGLY }enum_thing;
    class Thing {
        public:
            void thing(enum_thing elem){}
    };
}


using namespace NS;
int main() {
    Thing t;
    t.thing(BAD);
    return 0;
}

Test it yourself: http://codepad.org/Uw0XjOlF


Can you avoid using a typedef? Just do:

enum Foobar {good, bad, hello};


It should work. It does for me (the variant by Mystagogue should also work). I understand you had some other error messages ?

You probably just have to fix the header to be syntaxically correct, like putting a semi-colon at the end of class Thing, etc. When the header will be OK, the message about BAD not in namespace should also disappear.

0

精彩评论

暂无评论...
验证码 换一张
取 消