gpt4 book ai didi

c++ - 在枚举上重载 << 运算符会导致运行时错误

转载 作者:太空狗 更新时间:2023-10-29 23:29:57 24 4
gpt4 key购买 nike

就像这段代码:

#include <iostream>

enum class A {
a,
b
};

std::ostream& operator<<(std::ostream& os, A val)
{
return os << val;
}


int main() {
auto a = A::a;
std::cout << a;
return 0;
}

当我没有提供std::ostream& operator<<(std::ostream& os, A val)时该程序没有编译,因为 A::a 没有任何函数可以与 << 一起使用.但是现在当我已经提供它时,它会在我的终端和 ideone 上产生垃圾。 ,它会产生运行时错误(超出时间限制)。

最佳答案

std::ostream& operator<<(std::ostream& os, A val) {
return os << val;
}

这会导致无限递归。请记住 os << val真的被编译器看到了operator<<(os,val)在这种情况下。您要做的是打印枚举的基础值。幸运的是,有一个 type_trait 允许您公开枚举的底层类型,然后您可以将参数转换为该类型并打印它。

#include <iostream>
#include <type_traits>

enum class A {
a, b
};

std::ostream& operator<<(std::ostream& os, A val) {
return os << static_cast<std::underlying_type<A>::type>(val);
}

int main() {
auto a = A::a;
std::cout << a;
}

关于c++ - 在枚举上重载 << 运算符会导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35679280/

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