开发者

C++ implicit type conversion in Visual Studio 2010

I had a function: void foo(bool boolParam = true)

And I changed it to: void foo(const char* charParam, bool boolParam = true)

To avoid searching I just compiled the code hoping that the compiler will give an error (or at least an warning) where the function was called because of wrong parameter type, but instead of this the compiler silently converted false to NULL and compiled everything without error开发者_Go百科 or warning. Is this behavior correct? I know that false and NULL are both 0, but I think the compiler should give at least some warning message...


You could leave your original function unimplemented:

void foo(bool boolParam = true);
void foo(const char* charParam, bool boolParam = true)
{
  // do stuff
}

Now whenever you call foo(), foo(true), and foo(false) it will cause a compile error. However, foo(NULL) won't compile either because NULL and false are ambiguous (and then we are back to square one...).


The behavior is entirely correct, because (as you note) the conversion from false (a valid null pointer constant) to pointer is implicit. Try a std::string instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜