编程语言- c++在char *和bool之间的奇怪函数重载

programming languages - C++ weird function overloading between char * and bool

本文关键字:之间 重载 函数 bool c++ char 编程语言      更新时间:2023-10-16

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

我期待写(值?"yes": "no")将调用Write(conststring),但是,它调用Write(bool)。为什么?

#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是内置类型。