我有以下代码:
#include#include 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数组?
为什么C++在期望字符串时允许char数组作为参数?
因为std::string
有这样的转换构造函数,它支持隐式转换char const*
为std::string
对象.
这是负责此转换的构造函数:
basic_string( const CharT* s, const Allocator& alloc = Allocator());
看看文档和其他构造函数.