简体   繁体   中英

Representation of Month: enum class vs. class

I'm fairly new to C++, currently working through Stroustrup's Programming: Principles & Practice Using C++. I've read about 2/3rd of the book but because of lack of access to a PC for a while, am only just getting caught up on exercises. I'm currently working on the exercises in Chapter 9 where the reader is asked to create a Date class.

My simple Date class originally contained an enum class Month with the three letter abbreviation representing each month, so that the code I can write things like:

Month::jan

Which is much more descriptive than writing the integer 1, for example. This, as I understand it, is the primary purpose/advantage of using enum classes.

Now that I'm expanding the Date class to do things such as calculate the number of days from a given date, or the week number of a given date, I'm finding myself wanting to replace the enum class Month, with a class or struct that holds information about each month (eg name, abbreviated name, month number, and days in the month) and a container (vector is really the only one I'm comfortable using at this point) containing the 12 months. This would also allow me to write member functions that, from an organization perspective, would be better off within the scope of the Month class than the Date class.

If I change to this representation, however, I lose the convenience that the enum class provided when referring to months within the code, and instead have to write something like:

Month.Months(1) // where Months is the Month class member vector<Month>

So my question is, is there a way I can design my class that give me the best of both worlds? Thanks!

Fwiw, here is how I did it:

https://github.com/HowardHinnant/date/blob/master/date.h#L1671-L1682

CONSTDATA is just a backwards compatibility macro for constexpr . In case the link goes dead:

constexpr date::month jan{1};
constexpr date::month feb{2};
constexpr date::month mar{3};
constexpr date::month apr{4};
constexpr date::month may{5};
constexpr date::month jun{6};
constexpr date::month jul{7};
constexpr date::month aug{8};
constexpr date::month sep{9};
constexpr date::month oct{10};
constexpr date::month nov{11};
constexpr date::month dec{12};

If you don't have constexpr in your toolbox (requires C++11), you can use extern const and put the definition in a source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM