简体   繁体   中英

C++: Equivalent to “using namespace <namespace>” but for classes?

Suppose you have a class with an enum defined within it:

class MyClass {
  typedef enum _MyEnum{ a } MyEnum;
}

Is there a way to access the value a from another class without having to refer to it as MyClass::a? If the enum were contained within a namespace rather than a class, than "using namespace ;" solves the problem - is there an equivalent way to do this with classes?

I'm pretty sure you're stuck with "MyClass::a". Also... wouldn't doing this kind of defeat the purpose of putting the enum inside a class in the first place?

The best you can do is pull individual symbols into the class.

class SomeClass {
    typedef MyClass::MyEnum MyEnum;
    MyEnum value;
};

Note that if the typedef is in a public section of the class then anyone can refer to SomeClass::MyEnum as a synonym of MyClass::MyEnum .

An alternative would be to publically derive from an Enum-holder -class:

struct Holder {
    enum MyEnum { a };
};

class User : public Holder {
public:
    // a now visible in class
    MyEnum f() { return a; } 
};

// a visible outside too
User::MyEnum f() { return User::a; }

Unless that another class is a derived class of MyClass (and your enum is protected/public), no. I know this is not an answer but in my opinion the enum is defined inside MyClass for a reason, so don't try to make it globally available.

You can pull in each constant individually as follows:

class MyClass {
  public:
  // I added a value here intentionally to show you what to do with more than one enum value
  typedef enum _MyEnum{ a, b } MyEnum;
}
using MyClass::a;
using MyClass::b;
//... likewise for other values of the enum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM