C++中的enumC#中的非常的不同,最大的不同在于C++中的enum没有名字空间。

C#

class Program

    {

        enum Motion

        {

            Start,

            Running,

            Stopping

        }

 

        static void Main(string[] args)

        {

            Motion m = Motion.Running;

        }

}

 

 

C++

enum Motion

{

    Start,

    Running,

    Stopping

};

 

int _tmain(int argc, _TCHAR* argv[])

{

    Motion m = Running;

return 0;

}

 

见上例,在C++Motion并未起作用,使得enum内的元素全局有效,容易造成符号冲突。如下面的情况

enum Motion

{

    Start,

    Running,

    Stopping

};

 

void Start()

{

    //...

}

 

int _tmain(int argc, _TCHAR* argv[])

{

    Motion m = Running;

return 0;

}

这里就会报错误,提示Start重复定义。还有一种情况也很常见,

class C

{

public:

    enum Motion

    {

        Start,

        Running,

        Stopping

    };

 

    enum Status

    {

        Go,

        Stopping

    };

};

这里同样会提示错误,Stopping重复定义,这两种情况都没有比较好的解决方法。

*里提供了一些解决方法,我们可以在以后的实际中选择一个适合的折中的解决办法。

// oft seen hand-crafted name * solution
enum eColors { cRed, cColorBlue, cGreen, cYellow, cColorsEnd };
enum eFeelings { cAngry, cFeelingBlue, cHappy, cFeelingsEnd };
void setPenColor( const eColors c ) {
    
switch (c) {
        
default: assert(false);
        
breakcase cRed: //...
        breakcase cColorBlue: //...
        
//...
    }
 }


// (ab)using a class as a namespace
class Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
class Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
    
switch (c) {
        
default: assert(false);
        
breakcase Colors::cRed: //...
        breakcase Colors::cBlue: //...
        
//...
    }
 }


 
// a real namespace?
 namespace Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
 
namespace Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
 
void setPenColor( const Colors::e c ) {
    
switch (c) {
        
default: assert(false);
        
breakcase Colors::cRed: //...
        breakcase Colors::cBlue: //...
        
//...
    }
  }

原文见:

http://*.com/questions/482745/namespaces-for-enum-types-best-practices

 

 

分类:

技术点:

相关文章: