C++ 中的枚举未按预期工作,而是使用第一个值初始化

问题描述 投票:0回答:1

我有以下代码:

#include <iostream>

enum item_type {
    a,
    b
};

class item {
public:
    item_type type;
    item(item_type type) : type{type} {}
};

int main() {
    item a{a};
    item b{b};
    
    std::cout << a.type << " " << b.type;
    
    return 0;
}

我希望它输出

0 1
,但每次运行它时我都会得到
0 0

我发现当我申报这样的物品时:

item a{item_type::a};
item b{item_type::b};

...我的代码按预期运行。

有人能解释一下为什么吗?另外,为什么 c++ 在第一种情况下没有显示任何错误?

c++
1个回答
0
投票

这一行:

item a{a};

不使用枚举中的值初始化新的

a
对象,而是使用其自身。 它类似于:
int x = x;
;

所有常见编译器(MSVC、gcc、clang)都会对此发出警告。 例如。海湾合作委员会问题:

warning: 'a' is used uninitialized

参见现场演示

通过使用枚举范围,如下所示:

item a{item_type::a};

您实际上使用枚举值来初始化

a

同样适用于

b

© www.soinside.com 2019 - 2024. All rights reserved.