I have a class called time
which has day
, month
and year
.
I have a problem with returning the right value in my method, where it, depending on what we enter as a string "s"
it should return an int
value from one of those 3 fields.
So, for example, if I want to get days in my date I should call the function d["day"]
.
My question is, Is there something wrong with my code here? And, what should I put instead of
int operator[] (string s)
{
if (s == "day" || s == "month" || s == "year")
{
return ? ? ? ;
}
}
From the explanation, if I understood correctly, you need the following. You need to return appropriate member (i.e. either day
or month
or year
) according to the string match. (Assuming that you have mDay
, mMonth
, and mYear
as int
eger members in your Date
class)
int operator[] (std::string const& s)
{
if (s == "day") return mDay;
if (s == "month") return mMonth;
if (s == "year") return mYear;
// default return
return -1;
}
or alternatively using a switch
statement
// provide a enum for day-month-year
enum class DateType{ day, month, year};
int operator[] (DateType type)
{
switch (type)
{
case DateType::day: return mDay;
case DateType::month: return mMonth;
case DateType::year: return mYear;
default: return -1;
}
}