How to use Enum with strings in a function?
Basically, I have a Linked List which implements a display()
function that simply loops throught he elements and prints out their values.
I wanted to do it like this:
void List::display( std::string type )
{
switch(type)
{
// Do stuff...
The compiler immediately complained. My teacher said this would be because the string is not known at compile-time, resulting in an error. That explanation sounds a little iffy, but he suggested that I use enums. So I researched it and it says that explicit string to enums doesn't work. Something like
class List
{
enum type
{
HORIZONTAL = "inline"
VERTICAL = "normal"
}
and then, I really don't know.
The enum type
is a part of the List class, as well as the function display()
. This again looks like a really crappy solution. Nevertheless, I want to know if this approach is possible.
How could I set the enum in the main function at the same time开发者_JAVA技巧 I call display()? Like so
int main( void )
{
display("normal");
Of course, easier approaches are very welcome. In general, how do I declare/pass an enum to a function, if possible?
Switch, in current C++, only works with integral types. You could define your enum, switch on it, and write an auxiliary function that maps the enum to string values if needed.
Example
enum E { A, B };
string E_to_string( E e )
{
switch(e)
{
case A: return "apple";
case B: return "banana";
}
}
void display( E e )
{
std::cout << "displaying an " << E_to_string(e) << std::endl;
switch(e)
{
case A: // stuff displaying A;
case B: // stuff displaying B;
}
}
class List
{
enum Type
{
HORIZONTAL,
VERTICAL
};
void display(Type type)
{
switch (type)
{
//do stuff
}
}
};
int main()
{
List l;
l.display(List::HORIZONTAL);
}
精彩评论