代码之家  ›  专栏  ›  技术社区  ›  Hind Forsum

c++枚举作用域无法使用-std=c++98编译,但使用-std=c++11可以

  •  4
  • Hind Forsum  · 技术社区  · 6 年前

    #include<iostream>
    using namespace std;
    namespace m{
    class my{
    public:
        enum A{
            u=1,
            v=2,
            w=3
        };
        static A f(A a){
            return (A)(a + A::u);
        }
    };
    int main(){
        using namespace m;
        my::A r=my::f(my::u);
        return 0;
    }
    

    使用g++4.1.2编译:

    e.cpp:17:2: warning: no newline at end of file
    e.cpp: In static member function ‘static m::my::A m::my::f(m::my::A)’:
    e.cpp:11: error: expected primary-expression before ‘)’ token
    e.cpp:11: error: ‘A’ is not a class or namespace
    

    使用g++4.9.2和-std=c++98

    g++ e.cpp -std=c++98
    e.cpp: In static member function ‘static m::my::A m::my::f(m::my::A)’:
    e.cpp:11:36: error: ‘A’ is not a class or namespace
        static A f(A a){return (A)(a + A::u);}
                                        ^
    

    g++ e.cpp -std=c++11
    

    为了使用c++98进行编译,我将其更改为避免“A::”:

    static A f(A a){return (A)(a + u);}
    

    因此,在c++98中,嵌入的枚举类在类中是不可识别的,而在c++11中,它是可以工作的。这是枚举分辨率的不同,还是c++98标准中以前的一些语法错误?

    2 回复  |  直到 6 年前
        1
  •  3
  •   YSC    6 年前

    枚举值不受枚举类型的限制(无论是C++还是C++ 11)。在以下示例中:

    namespace N {
        enum E { X };
    }
    

    X N ::N::X .

    此行为由C++ 11改变,在遵循相同定义的情况下, 被引用使用 ::N::E::X

    [dcl.enum/11]

    在类作用域中声明的枚举数可以使用类成员访问来引用 :: , . -> (箭头)),见5.2.5。[示例:

    struct X {
        enum direction { left=’l’, right=’r’ };
        int f(int i) { return i==left ? 0 : i==right ? 1 : 2; }
    };
    
    void g(X* p) {
        direction d; // error: direction not in scope
        int i;
        i = p->f(left); // error: left not in scope
        i = p->f(X::right); // OK
        i = p->f(p->left); // OK
        // ...
    }
    

        2
  •  3
  •   StoryTeller - Unslander Monica    6 年前

    枚举名称不能用于在C++ 11之前限定枚举数。所以C++ 98模式中没有bug,代码只是格式不正确。

    你推断规则变了是对的。

    C++常见问题解答 lists the changes made to enumerations in C++11 ,并引用了推动这些变化的建议。