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

时间:2013-11-30 08:27:12

标签: c++

我有以下代码:

#include <iostream>
#include <string>

using namespace std;


string combine(string a, string b, string c);

int main() {

    char name[10]   = {'J','O','H','N','\0'};
    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;
}

尽管combine函数需要一个字符串并接收一个char数组,但编译没有警告或错误,这是因为字符串存储为char数组吗?

2 个答案:

答案 0 :(得分:6)

  

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

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

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

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

查看the documentation and other constructors

答案 1 :(得分:1)

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

string有一个像这样的构造函数(简化)

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

可以自动调用此构造函数,因此您的代码等同于此

cout << combine(string(name),age,location);