C++中的enum的名字空间

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重复定义,这两种情况都没有比较好的解决方法。

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

复制代码
代码
// oft seen hand-crafted name clash 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://stackoverflow.com/questions/482745/namespaces-for-enum-types-best-practices

 

 

posted @   connoryan  阅读(818)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示