考虑以下代码:
#include <iostream>
#include <string>
// void f(const char *) { std::cout << "const char *"; } // <-- comment on purpose
void f(const std::string &) { std::cout << "const std::string &"; }
void f(const void *) { std::cout << "const void *"; }
int main()
{
f("hello");
std::cout << std::endl;
}
我使用g++ (Ubuntu 6.5.0-1ubuntu1~16.04) 6.5.0 20181026
编译了这个程序:
$ g++ -std=c++11 strings_1.cpp -Wall
$ ./a.out
const void *
请注意,注释是为了测试而存在的,否则编译器会使用 f(const char *)
。
那么,为什么编译器会选择 f(const void*)
而不是 f(const std::string &)
?
最佳答案
转换为 std::string
需要“用户定义的转换”。
转换为 void const*
不会。
用户定义的转换在内置转换之后排序。
关于c++ - 为什么编译器更喜欢 f(const void*) 而不是 f(const std::string &)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354226/