我想將Weekday(周一至周五)表示為列舉,但不確定如何在 c 中表示資料。我做了一些閱讀并有我的列舉課:
enum Day{MONDAY=0, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};
但我還需要某種 to_string 方法,以便在需要時列印出日期。
目前,我Weekday在其自己的單獨類中表示 a ,如下所示:
Weekday::Weekday(char day){
switch(day){
case 'M' :
weekday = "Monday";
day_value = 0;
break;
case 'T':
weekday = "Tuesday";
day_value = 1;
break;
case 'W':
weekday = "Wednesday";
day_value = 2;
break;
case 'R':
weekday = "Thursday";
day_value = 3;
break;
case 'F':
weekday = "Friday";
day_value = 4;
}
}
但是當我向其他人展示我的代碼時,我得到了一些關注,所以我想知道這是否真的是最好的方法。
有人建議只使用一個開關來比較天數并完全避免開設新課程,但我認為這更有條理,如果我需要在作業日添加更多功能,這一切都已經設定好了。
I do have quite a few classes already for representing time in my program as well so maybe I am going a little crazy with the classes so I suppose I just need some guidance.
Their reasons for not using classes were something about memory and efficiency so thus I have three questions:
1.) Is a whole new class for a weekday the best way to represent this data?
2.)If a class of some sort is the best way what about an enum?
3.) Using an enum, how can I represent the enum data as a readable string I can print to an output later?
Sorry its a lot to unpack but I can't help but wonder if my way of making a class is truly the best way if there is a best way at all.
Regardless, thanks for the help in advance!
EDIT: the end goal here is to compare weekdays for example Monday comes before Tuesday so I assigned a value to the weekday and I would prefer not to use any imports
uj5u.com熱心網友回復:
我通常使用結構表:
struct Enum_Entry
{
enum Weekday day;
const char day_name[];
// or const char * day_name;
};
然后我有一個轉換表:
Enum_Entry conversion_table[] =
{
{MONDAY, "Monday"},
//...
{FRIDAY, "Friday"},
};
上表的一個好處是條目可以按任何順序排列。
一種不易維護的方法是使用名稱陣列:
static const char weekday_names[] =
{ "Monday", /*...*/, "Friday"};
轉換方法:
std::cout << weekday_names[WEDNESDAY] << "\n";
兩者都不是最好的方法,它們各有優缺點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425977.html
