C ++将字符串隐式转换为char *匹配错误的函数签名

Aar*_*ron 2 c++ char stdstring implicit-cast

我正在编写一个程序,该程序应该处理c字符串(char *)和c ++字符串(std :: string)。我出于关注而孤立了以下示例。

#include <iostream>
#include <string>

void hello(std::string s) {
    std::cout << "STRING FUNCTION" << std::endl;
}

void hello(char* c) {
    std::cout << "CHAR FUNCTION" << std::endl;
}

int main(int argc, char* argv[]) {
    hello("ambiguous");
    hello((std::string)"string");
    hello((char*)"charp");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我编译该程序时,我得到警告:

test.cpp:14: warning: deprecated conversion from string constant to ‘char*’
Run Code Online (Sandbox Code Playgroud)

关于首次致电hello。运行该程序可以得到:

CHAR FUNCTION
STRING FUNCTION
CHAR FUNCTION
Run Code Online (Sandbox Code Playgroud)

显示对的第一个调用hello与签名匹配hello(char* c)

我的问题是,如果作为c ++程序,字符串文字("ambiguous")是std :: string,为什么将其强制转换为a char*然后匹配函数,hello(char* c)而不是停留在std :: string和match之上hello(std::string s)

我知道我可以进行杂注或-发出警告(并且我可以将char *转换为字符串而无需担心),但是我想知道为什么编译器甚至还要麻烦地执行此转换,以及是否有一种方法可以告诉它不要。我正在使用g ++ 4.4.3进行编译。

谢谢。

Gri*_*zly 5

像这样的字符串文字"ambiguous"不是type std::stringstd::string是仅库类型,没有任何语言魔力。字符串文字的类型实际上是const char[N],其中N文字的长度。

由于历史原因(向后兼容),字符串文字将隐式转换为char*(违反const-correctness)。此内置转换优先于的“用户定义”转换std::string,这就是为什么它调用char*函数并给您警告的原因。

如果将的签名更改hellohello(const char* c),则可能不会再发出警告(但仍不会调用该std::string版本,因此您需要手动强制转换)。