"Invalid conversion" error with conditional operator
I'm getting compile error in this line:
cout << (MenuItems[i].Checkbox ? (MenuItems[i].Value ? txt::mn_yes : txt::mn_no) : MenuItems[i].Value)
Error:
menu.cpp|68|error: invalid conversion from 'int' to 'const char*'
menu.cpp|68|error: initializing argument 1 of 'std::开发者_开发技巧basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]'
MenuItems is std::vector of following class:
class CMenuItem
{
public:
string Name;
int Value;
int MinValue, MaxValue;
bool Checkbox;
CMenuItem (string, int, int, int);
CMenuItem (string, bool);
};
mn_yes and mn_no are std::strings.
Compiler is MinGW (version that is distributed with code::blocks).
The two possible conditional values have to be convertible to a common type. The problem is that the left of the outer conditional:
(MenuItems[i].Value ? txt::mn_yes : txt::mn_no)
is always a string
, but the right:
MenuItems[i].Value
is an int. It tries to find a way by going const char *
->string
, but then it won't allow the int
to const char *
conversion (which is good, because it would be meaningless). Just do:
if(MenuItems[i].Checkbox)
{
cout << (MenuItems[i].Value ? txt::mn_yes : txt::mn_no);
}
else
{
cout << MenuItems[i].Value;
}
or similar.
精彩评论