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

文章目录

  • 前言
  • 一、发生的场景
  • 二、解决方法
    • 1.显式声明其中一个为std::string类型(推荐写法)
    • 2.去掉+,让编译器拼接字符串(不推荐)
  • 三、验证


前言

在使用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;

解决error: invalid operands of types ‘const char [6]‘ and ‘const char [6]‘ to binary ‘operator+‘_第1张图片

你可能感兴趣的:(C/C++,c++,字符串,string)