gpt4 book ai didi

c++ - 如果 int 是 "not within the enums range",为什么将其转换为强类型枚举会编译?

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:41 24 4
gpt4 key购买 nike

<分区>

在下面的代码中,我使用 static_cast 将强类型 enum 转换为 int。另一个方向也一样。但如果转换 int 不在 enum 范围内,它也有效。为什么会这样,为什么编译器没有捕捉到这个?

#include <iostream>
#include <string>

enum class Name {Hans, Peter, Georg}; // 0, 1, 2

std::string getName(Name name) {
switch(name) {
case Name::Hans: return "Hans";
case Name::Peter: return "Peter";
case Name::Georg: return "Georg";
default: return "not valid name";
}
}

int main()
{
// Cast a Name to an int, works fine.
std::cout<< static_cast<int>( Name::Peter ) <<std::endl; // 1
std::cout<< static_cast<int>( Name::Hans ) <<std::endl; // 0

// Cast an int to a Name
std::cout<< getName(static_cast<Name>(2)) <<std::endl; // Georg
std::cout<< getName(static_cast<Name>(3)) <<std::endl; // not a valid name
// I would expect a compiler error/warning like i get here:
// std::cout<< static_cast<int>( Name::Hans + 4 ) <<std::endl;
}

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