枚举的用法 - 全局和本地

时间:2016-06-06 11:52:38

标签: c++ enums global local

我只是尝试使用与本地定义相同名称的全局定义的枚举。

除了起点之外,我已经初始化了相同的值。

enum Day {Sunday = 1 ,Monday,Tuesday,Wednesday,Thursday,Friday /*= 15 */,Saturday};

void enumUse() {
    enum Day {Sunday = 2 ,Monday,Tuesday,Wednesday,Thursday,Friday /*= 15 */,Saturday};
    Day today = Tuesday;
    cout<<Sunday<<endl;
    cout<<Monday<<endl;
    cout<<Tuesday<<endl;
    cout<<Wednesday<<endl;
    cout<<Thursday<<endl;
    cout<<Friday<<endl;
    cout<<Saturday<<endl;
    cout<<"Today: "<<today;
    cout<<endl;
}

此代码段提供本地枚举的输出。

如果将其注释掉,则会提供与全局相关的输出。

如何在不评论本地枚举的情况下使用全局枚举。

1 个答案:

答案 0 :(得分:1)

您可以使用范围解析运算符,因为全局范围内定义了全局Day

//'Day' from global scope
::Day today = ::Tuesday; //'Tuesday' also needs it because it would take the local one,
                         //which can't be assigned to the global 'Day' (they're different
                         //enums after all)