gpt4 book ai didi

c++ - 在 C++98 和 C++11 中访问枚举值

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:14 24 4
gpt4 key购买 nike

我在“Foo”类(如下)中定义了一组枚举值。

namespace Fii
{
class Foo
{
struct Bar
{
enum Baz
{
BAZ1,
BAZ2,
BAZ3
};
};
};
};

我正在使用一个结构来缩小 Baz 枚举值的范围,并显示有一组相关值。

我的目标是将一个枚举类型的值赋给一个变量。使用上面的类定义,可以这样做:

Fii::Foo::Bar::Baz myValue = Fii::Foo::Bar::BAZ1 (Works in both C++98 and C++11)

但是,我觉得:

  • 乍一看,myValue 似乎被初始化为一个 Fii::Foo::Bar 但这只是因为枚举是对父级(Bar 在这种情况下)

为了提高准备度,我将代码重构为:

namespace Fii
{
class Foo
{
enum Baz
{
BAZ1,
BAZ2,
BAZ3
};
};
};

使用这个新的类定义,可以这样做:

Fii::Foo::Baz myValue = Fii::Foo::Baz::BAZ1 (Works in C++11 only)
Fii::Foo::Baz myValue = Fii::Foo::BAZ1 (Should work on C++98 and C++11 - not tested)

问题 1) 为什么 Fii::Foo::Bar::Baz myValue = Fii::Foo::Baz::BAZ1 仅适用于 C++11?

Q2) 在 C++98 中,有没有办法编写 Fii::Foo::Baz myValue = Fii::Foo::Baz::BAZ1 ?您可以在类定义中进行任何您喜欢的更改。

环境:- 支持 C++11 的 Clang 编译器- 代码 4- Mac 操作系统 10.8

最佳答案

C++11 添加了 class enums .它还添加了一种访问旧式枚举值的新方法,这就是您在此处看到的。

enum Foo { FOO1, FOO2, FOO3 }; // old-style enum

Foo f1 = Foo::FOO1; // OK in C++11, error in C++98.
Foo f2 = FOO1; // OK in C++98 and C++11 (for backward compatibility)

关于c++ - 在 C++98 和 C++11 中访问枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12381880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com