开发者

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

开发者 https://www.devze.com 2022-12-11 00:06 出处:网络
Suppose you have a 开发者_StackOverflowclass with an enum defined within it: class MyClass { typedef enum _MyEnum{ a } MyEnum;

Suppose you have a 开发者_StackOverflowclass 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
0

精彩评论

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