枚举 输入流重载>> C++

语言:C++

我们可能会遇到这种情况:自己定义了一个枚举类型,但是却不知道如何重载输入流,使我们定义的枚举用起来不是很方便。

那么,如何去重载呢,我们先来看一下内置类型的测试过程:

#include<iostream>
using namespace std;

int main()
{
    bool b;
    cin >> b;
    if (b == true)
        cout << "YES" << endl;
        
        return 0;
}

 

当我们输入  1   

输出将会是   YES

当我们输入  true

什么都不会输出

 

 

当然,C++库里面有相关的格式控制,一般,我们输出bool类型的量输出的是数字,格式控制之后可以显示true和false,这里我们不做这方面的讨论。

那么,我们就上述的情况可知,一般情况下,我们输入的时候通常输入一个整型的值。

这样我们就可以这样写:

#include<iostream>
using namespace std;

enum TYPE_ { Tricycle = 0, Van, taxi, truck, Coupe };//车辆类型

istream& operator>>(istream& is, TYPE_& rhs)
{
    int n;
    is >> n;
    rhs = TYPE_(n);
    return is;
}

int main()
{
    TYPE_ t;
    cin >> t;
    if (t == taxi)
        cout << "该枚举量为taxi" << endl;

    return 0;
}

我们 来测试一下:

 

 

没有问题

 

posted @ 2018-01-22 11:15  林-兮  阅读(661)  评论(2编辑  收藏  举报