关于“ 以前的定义是“枚举数” ”问题的解决办法

来源:互联网 发布:ccn是什么网络 编辑:程序博客网 时间:2024/05/02 00:41

       相信在学习C++的过程中,很多人都遇到过 名字空间 (namespace)这个名词,其实说简单一点,名字空间就是将各种名称封装在不同的包里面,以免命名重复。

其解决的最主要的问题就是命名重复。好了,既然说到这里,相信也知道该如何解决这个问题了。现举例如下:

namespace OCC{enum Occupation{ administrator = 0,artist = 1,doctor = 2,educator = 3,engineer = 4,entertainment = 5,executive = 6,healthcare = 7,homemaker = 8,lawyer = 9,librarian = 10,marketing = 11,none = 12,other = 13,};}namespace GEN {enum Gender{male = 0,female = 1,other = 2};}

       以上两个枚举中,都存在other,如果放在同一命名空间中会存在 重定义问题 ,现在将其放在两个空间中,就可以解决命名重复问题,但需要注意调用的方法。调用如下:

调用方法一:

using namespace OCC;using namespace GEN;int a = Occupation::other;int b = Gender::other;

调用方法二:

int a = OCC::Occupation::other;int b = GEN::Gender::other;

调用方法三:

       也可以直接忽略enum的命名,而将两个枚举类型定义为 未命名枚举 ,同时将 命名空间 的名字改为原枚举类型的名称,举例如下:

namespace Occupation{enum { administrator = 0,artist = 1,doctor = 2,educator = 3,engineer = 4,entertainment = 5,executive = 6,healthcare = 7,homemaker = 8,lawyer = 9,librarian = 10,marketing = 11,none = 12,other = 13,};}namespace Gender {enum {male = 0,female = 1,other = 2};}int a = Occupation::other;int b = Gender::other;

       额外:如果在同一命名空间时,即使如下使用,仍会出现 重定义问题:

int a = Occupation::other;int b = Gender::other;


原创粉丝点击