编程语言- c++在char *和bool之间的奇怪函数重载
programming languages - C++ weird function overloading between char * and bool
下面的测试程序有两个名称相同,参数类型不同的函数。我通过传递一个条件表达式作为参数来调用函数。
我期待写(值?"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
是内置类型。
相关文章:
- 构造函数和转换运算符之间的重载解析
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 你能帮我了解重载一元运算符和二进制运算符之间的区别吗?
- 将重载构造函数传递给类之间的函数
- C++模板和非模板函数之间的重载解析
- C++ 类的构造函数和函数调用运算符 () 重载之间的歧义
- 函数隐藏和重载之间的区别
- 模板流运算符重载错误:引用初始化无效,与basic_istream和basic_ifstream之间的差异有关
- Int64 和 time_t 之间的 C++ 重载歧义
- 函数重载和双精度和长之间的混淆
- 基类和派生类中的模板成员之间的重载解析
- 如何在两个不同的类之间重载"=="运算符?
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 模板专用类之间的构造函数重载
- C++ 中多态性和函数重载之间的区别
- 指针之间的运算符重载
- C++:使用结构或枚举重载构造函数之间的区别
- 重载和对象定向之间的关系
- ostream 插入运算符与其非成员重载之间的关系
- c++中按引用传递和按值传递之间重载歧义的实用解决方案