jeudi 27 janvier 2022

Using Enum to represent days

I want to represent a Weekday (Monday to Friday) as an enum but am not sure how to represent the data in c++. I have done some reading and have my enum class:

enum Day{MONDAY=0, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};

But I also need some sort of to_string method in order to print the days out when required.

Currently I represent a Weekday in its own separate class as shown below:

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

}

But I got a few looks when presenting my code to others so I was wondering if this is really the best way to do it.

Someone suggested to just use a switch to compare days and avoid making a new class at all but I thought this is more organized and on the plus side if I ever need to add more functionality to a weekday its all already set up.

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

Aucun commentaire:

Enregistrer un commentaire