C ++枚举范围无法使用-std=c ++ 98进行编译,但使用-std=c ++ 11可以
c++ enum scope failed to compile with -std=c++98, but ok with -std=c++11
一个简单的程序如下,根本没有c ++ 11语法(e.cpp(
#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);}
^
但是使用 -std=c++11 是可以的:
g++ e.cpp -std=c++11
为了使它使用 c++98 编译,我将其更改为避免"A::"为:
static A f(A a){return (A)(a + u);}
因此,在 c++98 下,嵌入式枚举类在类中无法识别,而在 c++11 中它可以工作。这是枚举分辨率的差异,还是 c++98 标准中的一些先前语法错误?
枚举值不受枚举类型的作用域(在 C++98 或 C++11 中(。在以下示例中:
namespace N {
enum E { X };
}
X
直接在命名空间N
的范围内。其完全限定标识符将::N::X
。
C++11 更改了此行为,其中遵循相同的定义,也可以使用::N::E::X
引用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 // ... }
—结束示例 ]
枚举名称不能用于限定 C++11 之前的枚举器。所以 C++98 模式下没有错误,代码只是格式不正确。
你推断规则已经改变是正确的。
C++常见问题解答列出了对 C++11 中的枚举所做的更改,并引用了推动这些更改的建议。
相关文章:
- std::is_base_of表示ctor编译错误
- 关于std::move的使用,是否有编译警告
- std::experimental::source_location 在编译时
- C++如果必须在编译时确定大小,std::array 有什么意义?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- std::cout输出int时出现编译错误
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- std::unique_ptr 在 GCC 中工作,但不能在 Visual Studio 中编译
- 确保编译时的特定 std::array 位置
- 编译器不会使用 -std=c++11 编译智能指针
- GCC 8.3 无法编译 std::bind_front
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 使用 CImg 库的 std::min 和 std::max 的编译问题
- std::less是否应该允许在编译时比较不相关的指针?
- 为什么 std::make_shared 无法编译带有已删除运算符 new 的类型?
- std::variant<>::get() 不能使用 Apple LLVM 10.0 编译
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- QString和stdstring组合在std::编译错误中不起作用
- 使用typedef和std编译错误
- std::编译期间设置的数组类成员