解决error: invalid operands of types ‘const char [6]‘ and ‘const char [6]‘ to binary ‘operator+‘

本文介绍了在C++中尝试使用+运算符连接两个const char*类型字符串时遇到的错误,即`invalid operand of types 'const char[6]' and 'const char[6]' to binary 'operator+'`。错误发生的原因是C++将双引号包围的字符串视为const char*类型,而不是std::string。解决方法包括显式将其中一个转换为std::string类型或者利用编译器的字符串字面量连接特性。文章提供了验证不同连接方式的正确示例。


前言

在使用C++中的字符串时,习惯性的把两个使用""括起来的字符串使用+连接,结果报错error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'
意思是对两个const char*类型的操作数进行+运算是非法的,本来想着两个字符串能够像c++中的string一样进行连接,结果与自己想的大相径庭。


一、发生的场景

在这里插入图片描述

	//std::string str = "hello" + "world"; // error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'
	//std::string str = std::string("hello") + " world"; // 正确
	//std::string str = "hello" + std::string("world"); //正确
	std::string str = "hello"" world"; //正确

    cout << "str=" << str << endl;

使用+运算符连接两个使用""包裹的字符串时报错。原因是在C++中,""括起来的字符串被当成是const char*类型,而非string类型。

二、解决方法

参考stackoverflow上的解释,详细内容请阅读error: invalid operands of types ‘const char*’ and ‘const char*’ to binary ‘operator+’

1.显式声明其中一个为std::string类型(推荐写法)

std::string str = std::string("hello") + " world";

2.去掉+,让编译器拼接字符串(不推荐)

std::string str = "hello"" world";

大多数编译器会自动拼接""包围的字符串,但不保证所有的编译器都正常。推荐显示声明为string类型的字符串再进行+操作。


三、验证

	std::string str1 = std::string("hello") + " world" + "!"; // 正确
    std::string str2 = "hello" + std::string(" world") + "!"; //正确
    std::string str3 = "hello"" world" "!"; //正确

    cout << "str1=" << str1 << endl;
    cout << "str2=" << str2 << endl;
    cout << "str3=" << str3 << endl;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值