I've been working with C on a Time class in Qt and I need to write an enum class
that contains the formats that I use in showTime()
. Because of the nature of the QString
formats I've been getting the following error, the value is not convertible to 'int'
. I would gladly appreciate any help or suggestions.
P.S: Here's the code:
enum class TimeFormat {
a = "hh:mm:ss",
b = "hh:mm",
c = "H:m:s a"
};
class Time {
public:
Time();
~Time();
void setTime(QTime t);
QString showTime(){
return time->toString(format);
}
private:
QTime* time;
TimeFormat format;
};
CodePudding user response:
The enumeration underlying type must be an integer type. So you couldn't use char const*
for that. In your case, you could use a private array associated with your enumerations:
class Time {
public:
enum class Format {
a, b, c
};
public:
Time();
~Time();
void setTime(QTime t);
QString showTime(Format const f){
time->toString(format.at(static_cast<size_t>(f));
}
private:
QTime* time;
static inline std::array<char const*, 3> constexpr format =
{ "hh:mm:ss", "hh:mm", "H:m:s a" };
};
CodePudding user response:
enumeration underlying type must be an integer type. It can't be a string. You can associate string with an enumeration value using sone code.
Example (minimum C 17):
enum class TimeFormat {
a,
b,
c
};
constexpr std::string_view toStringFormat(TimeFormat format)
{
using namespace std::literals;
constexpr std::array formats{ "hh:mm:ss"sv, "hh:mm"sv, "H:m:s a"sv};
return formats[static_cast<size_t>(format)];
}
https://godbolt.org/z/Y6P6Wa4K5
CodePudding user response:
Enum's underlying type must be an integer in C
, but Swift
and Java
languages support something like what you tried.
Anyway, try something like below.
my-time.h
file:
enum TimeFormat {
a,
b,
c
};
class Time {
public:
Time();
~Time();
void setTime(QTime t);
QString showTime();
private:
QTime* time;
TimeFormat format;
};
my-time.cpp
file:
#include "my-time.h"
const char * const FORMAT_STRING_MAP[] = [
"hh:mm:ss",
"hh:mm",
"H:m:s a"
];
QString Time::showTime()
{
time->toString(FORMAT_STRING_MAP[format]);
}
CodePudding user response:
I used a switch statement
enum class TimeFormat {
format1,
format2,
format3,
};
class Time {
public:
Time();
~Time();
void setTime(int h, int m, int s);
QString showTime() const{
QString f;
switch (format) {
case TimeFormat::format1:
f="hh:mm:ss";
break;
case TimeFormat::format2:
f = "hh:mm";
break;
case TimeFormat::format3:
f= "H:m:s a";
break;
}
return time->toString(f);
}
void changeFormat(TimeFormat f);
private:
QTime* time;
TimeFormat format;
};