gpt4 book ai didi

C++11 枚举类 : plus int failed to compile, 为什么?

转载 作者:行者123 更新时间:2023-11-30 00:44:47 25 4
gpt4 key购买 nike

我有一个快速代码片段:

#include<iostream>
using namespace std;
enum class A:int {
u=1,
v=2,
w=3
};
template<A value>
int nextEnum(){
return value+1;
}
int main() {
nextEnum<A::u>();
return 0;
}

编译失败:

clang++ testenum.cpp -std=c++11
testenum.cpp:10:17: error: invalid operands to binary expression ('A' and 'int')
return value+1;

好吧,我已经将 A 声明为“int”枚举,为什么它不能用 int 来“+”?如何解决?

最佳答案

enum class 不能隐式转换为整数。你必须使用 static_cast,例如:

template <A value>
A nextEnum() {
return static_cast<A>(static_cast<int>(value) + 1);
}

关于C++11 枚举类 : plus int failed to compile, 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46948316/

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