gpt4 book ai didi

c++ - 为什么 C++ 在需要字符串时允许将 char 数组作为参数?

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:30 25 4
gpt4 key购买 nike

我有以下代码:

#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 数组吗?

最佳答案

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

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

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

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

看看the documentation and other constructors .

关于c++ - 为什么 C++ 在需要字符串时允许将 char 数组作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20298172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com