开发者

Default enum visibility in C++

I have a class that looks like this:

namespace R 
{
class R_Class 
{
   enum R_Enum
   {
       R_val1,
       R_val2,
       R_val3开发者_运维问答
   }
private:
   // some private stuff
public: 
  // some public stuff
}
}

I'm performing unit testing using an automated test tool. The compiler claims that my test harness cannot access the type R::R_Class::R_Enum.

I have no trouble accessing the values within a similar class that is defined as such:

namespace S
{
class S_Class
{
public:
   enum S_Enum
   {
       S_val1,
       S_val2,
       S_val3
   }
}
private:
   // some private stuff
public: 
  // some public stuff
}

Do enums in C++ need to be given explicit visibility directives? If not given any, do they default to private? protected?


enums obey visibility in classes just like attributes, methods, nested classes or anything else. You need to make it public for outside visibility.

This is so that classes can have private enums used by its own private methods without exposing the enum values to the outside world.


All class members, enum or otherwise, are private if you don't specify otherwise. Similarly, all struct members are public if you don't specify otherwise.


If an enum needs to be public, should you nest it inside another class? I found it convenient and self-documenting to put enums in their own namespace but not another class. You treat the namespace sort of like a class name and you ignore the actual enum name. This allows you to give enum members really good names without conflicting or having to use the hungarian naming approach. In your question, for example, if we have a namespace LedState and an enum State with members On and Off, then you just use LedState::On or LedState::Off. With a typedef outside the LedState namespace, like:

 typedef LedState::State LedStateType 

you can ignore the actual name of the enum "State" so that name can be reused without conflict. If you need to pass an enum, you just declare it of type LedStateType. I wrote a more complete example in a recent blog entry.


An enum defined within class scope follows the access rules that applies to everything else in class scope. You need to place the enum in a public: section in order for the type to be accessible outside the class.


They don't default any different than any other member. Since private is the default, that applies to enums just as it would to any other member. Not sure why you think the behavior you're seeing has anything to do with the fact that the member is an enum.


I assumed that all class members are private by default and I was surprised to discover that structs are the exception.

Related question on SO: default visibility of C++ class/struct members


private is the default accesibility of C++ classes of classtype 'class'. If you omit specifying it, you cannot access it from the outside of your class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜