char * 和 bool 之间的 C++ 怪异函数重载

C++ weird function overloading between char * and bool

下面的测试程序有两个同名的函数,不同的参数类型。我通过将条件表达式作为参数传递来调用该函数。

I'm expecting Write(value ? "yes" : "no") will call Write(const string), however, it calls Write(bool). Why?

#include <iostream>

using namespace std;

void Write(const string value)
{
  cout << "String" << endl;
}

void Write(bool value)
{
  cout << "Bool" << endl;
}

int main()
{
  bool value = false;

  Write(value ? "yes" : "no");

  return 0;
}

您可以通过更换

来解决您的问题
Write(value ? "yes" : "no");

来自

Write(string(value ? "yes" : "no"));

问题如下:您没有定义将 char* 作为参数的函数,因此必须进行隐式转换。但是,隐式转换为 bool 而不是 std::string,因为 bool 是内置类型。