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

 squareEnxi_571 发布于 2023-02-13 17:51

我有以下代码:

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

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

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

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

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

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

    2023-02-13 17:54 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有