怎么我重载<<输出枚举的字符串值

时间:2016-11-24 06:28:22

标签: c++ enums

实施代表星期几的课程日。重载运算符+ =,operator- =,operator ++(前缀)和operator--(前缀),以及运算符<<如下所述。

我会在重载的<<中使用switch语句吗?定义cout枚举的字符串值?主要代码是测试我们的代码是否正常运行(仍然需要完成运算符的定义) 我应该回复enum和int之间的隐式转换吗?我不知道如何将枚举放入参数中(如果那些甚至合适)

这是我的代码:

/*
Class Implementation for Day of the week
includes overloaded operators 
*/

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;



class Day
{
public:
    enum Dia { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
    Day(int); // Default Constructor
    Day(const Day&); // Copy Contructor
    Day& operator+=(const Day&); // Overloaded +=
    int getDummy() const;
private:
    int dummyDay;
};

std::ostream& operator<<(std::ostream&, const Day&);


int main()

{
    Day today = Day::WEDNESDAY;
    cout << today;
    std::cout << today << std::endl; // "Wednesday"

    Day generic_day; // default constructor-- default day is Sunday
    std::cout << generic_day << std::endl; // "Sunday"

    ++generic_day;
    std::cout << generic_day << std::endl; // "Monday"

    today += 5;
    std::cout << today << std::endl; // "Monday"

    today -= 1;
    std::cout << today << std::endl; // "Sunday
    return 0;
}
Day::Day(int DayDay = 0)
{
    dummyDay = DayDay;
};

Day& Day::operator+=(const Day& z)
{
    dummyDay += z.dummyDay;
    return *this;
}
std::ostream& operator<<(std::ostream& out, const Day& z)
{

    return out;
}

Day::Day(const Day& z)
{
    dummyDay = z.dummyDay;
}

int Day::getDummy() const
{
    return dummyDay;
}

2 个答案:

答案 0 :(得分:2)

您可能希望使用std::vector<std::string>来存储所有工作日的字符串。 std::vector<std::string> weekOfDay = {"Monday", etc...};

甚至更好,正如@celtschk所指出的那样std::array<std::string, 7>是一个更轻松的选择。

然后,您可以使用oss << weekOfDay[day.getDummy()] oss std::ofstream来获取当天的当天。

如果您无法使用std::vectorstd::array或C ++ 11功能,请使用简单的std::string数组。

答案 1 :(得分:2)

您可以重载enum。您不需要创建一个全新的类,只需为enum创建重载并随时调用它们;查看main函数中的用法。将C ++ 11与enum class一起使用并实现以下内容,我测试了它并且它正在运行:

#include <iostream>

using namespace std;

enum class Day
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

Day& operator++(Day& day)
{
    int i = static_cast<int>(day) + 1;

    // Handle wrap around.
    if(i > 6)   // Saturday = 6
        i = 0;  // Sunday = 0

    day = static_cast<Day>(i);

    return day;
}

ostream& operator<<(ostream& os, const Day day)
{
    switch(day)
    {
        case Day::Sunday:    return os << "Sunday";
        case Day::Monday:    return os << "Monday";
        case Day::Tuesday:   return os << "Tuesday";
        case Day::Wednesday: return os << "Wednesday";
        case Day::Thursday:  return os << "Thursday";
        case Day::Friday:    return os << "Friday";
        case Day::Saturday:  return os << "Saturday";
    }

    return os;
}

int main()
{
    Day day = Day::Monday;
    cout << day << endl;

    ++day;
    cout << day << endl;

    return 0;
}