default argument mismatch in C++?
-
26-06-2021 - |
Pregunta
Consider the following code:
#include <iostream>
class Bar
{
public:
void foo(bool b = false, std::string name = "");
};
void Bar::foo(bool b, std::string name)
{
if (!b)
{
std::cout << "b is false" << std::endl;
}
else
{
std::cout << "b is true" << std::endl;
}
}
int main()
{
Bar myBar;
myBar.foo("bla");
return 0;
}
I guess C++ is not broken, but can anyone please explain why the output is true? I am working on VS 2010 but I also checked in ideone which runs gcc
Solución
The compiler is implicitly casting the first parameter, a char const[4]
, to bool
, and results in true
.
It's equivalent to
myBar.foo((bool)"bla");
which is also equivalent to
myBar.foo((bool)"bla", "");
Otros consejos
Because the "bla"
is a char const[4]
, which decays to const char*
, and is cast to a bool. Since it's value is not 0
, the cast takes the value true
. A simpler example:
#include <iostream>
int main()
{
std::cout << std::boolalpha; // print bools nicely
bool b = "Hello";
std::cout << b << "\n";
}
produces
true
Bool parameter convert "bla" to true. You need to change order of your parameters.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow