gpt4 book ai didi

c++ - 我如何重载 << 以输出枚举的字符串值

转载 作者:行者123 更新时间:2023-11-27 22:48:16 24 4
gpt4 key购买 nike

实现代表一周中某一天的 Day 类。重载 operator+=、operator-=、operator++(前缀)、operator--(前缀)和 operator<<,如下所述。

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

这是我的代码:

/*
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;
}

最佳答案

您可以重载枚举。您不需要创建一个全新的类,您只需为 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;
}

关于c++ - 我如何重载 << 以输出枚举的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40779407/

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