enum class的输出重载

之前纠结enum class,其中一个问题就是,要输出type的名字,方便调试。
今天尝试了一下输出重载,没想到竟然可以。
测试如下,

#include <iostream>
using namespace std;

enum class Type
{
    TEXT,
    _EOF
};

ostream& operator << (ostream& out,Type tp)
{
    switch(tp)
    {    
        case Type::TEXT:
            out << " TEXT ";break;
        case Type::_EOF:
            out << " _EOF ";break;
        default:;
    }
    return out;
}

int main()
{
    Type A = Type::TEXT;
    Type B = Type::_EOF;
    cout << A << B << endl;
    return 0;
}

还是Python的__name__好用啊。

转载于:https://www.cnblogs.com/Frandy/archive/2012/10/13/enum_class_cout.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您的结构体中包含 QMap<自定义枚举类型, QMap<自定义枚举类型, 子结构体>>,则需要分别为该结构体、子结构体以及自定义枚举类型定义等号和不等号运算符。 先来看自定义枚举类型的重载运算符。假设该枚举类型的名称为 MyEnum,需要按照以下方式定义 == 和 != 运算符: 复制 enum class MyEnum { A, B, C }; bool operator==(const MyEnum& lhs, const MyEnum& rhs) { return static_cast<int>(lhs) == static_cast<int>(rhs); } bool operator!=(const MyEnum& lhs, const MyEnum& rhs) { return !(lhs == rhs); } 在上述代码中,我们将 MyEnum 转换为 int 类型进行比较,因为 enum class 默认没有定义等号和不等号运算符。 接下来是子结构体的重载运算符,假设子结构体的名称为 SubStruct,包含两个整数 x 和 y,则需要按照以下方式定义 == 和 != 运算符: 复制 struct SubStruct { int x; int y; bool operator==(const SubStruct& other) const { return x == other.x && y == other.y; } bool operator!=(const SubStruct& other) const { return !(*this == other); } }; 最后是包含 QMap<自定义枚举类型, QMap<自定义枚举类型, SubStruct>> 的结构体的重载运算符,假设该结构体的名称为 MyStruct,需要按照以下方式定义 == 和 != 运算符: 复制 struct MyStruct { QMap<MyEnum, QMap<MyEnum, SubStruct>> aa; bool operator==(const MyStruct& other) const { return aa == other.aa; } bool operator!=(const MyStruct& other) const { return !(*this == other); } }; 在上述代码中,我们直接利用了 QMap 的默认等号运算符,因为其已经对子结构体进行了深度比较。因此,我们只需要为 MyStruct 定义等号和不等号运算符,将其与其他 MyStruct 对象进行比较即可。,你的这种方法系统会报错
06-18

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值