为什么C++允许 char 数组作为参数,当它需要一个字符串时?

Why does C++ allow a char array as an argument when it's expecting a string?

本文关键字:一个 字符串 数组 char 允许 C++ 参数 为什么      更新时间:2023-10-16

我有以下代码:

#include <iostream>
#include <string>
using namespace std;

string combine(string a, string b, string c);
int main() {
    char name[10]   = {'J','O','H','N',''};
    string age      = "24";
    string location = "United Kingdom";

    cout << combine(name,age,location);
    return 0;
}
string combine(string a, string b, string c) {
    return a + b + c;
}

尽管组合函数期望一个字符串并接收到一个char数组,但它编译得很好,没有警告或错误,这是因为字符串存储为char数组吗?

为什么C++在期望字符串时允许使用char数组作为参数?

因为std::string有这样一个转换构造函数,它支持将char const*隐式转换为std::string对象。

这是负责此转换的构造函数:

basic_string( const CharT* s, const Allocator& alloc = Allocator());

看看文档和其他构造函数。

这是因为有一个从char数组到字符串的自动转换。

string有一个类似(简化的)的构造函数

class string
{
public:
    string(const char* s);
    ...
};

这个构造函数可以自动调用,所以你的代码相当于这个

cout << combine(string(name),age,location);
相关文章: