【问题标题】:String concatenation using + operator [duplicate]使用 + 运算符的字符串连接 [重复]
【发布时间】:2015-10-23 11:26:05
【问题描述】:
std::cout << "Please enter your first name: ";
std::string name;
std::cin >> name;
// build the message that we intend to write
const std::string greeting = "Hello, " + name + "!"; //LineA
std::cout << greeting;

产品:

你好,anyname_given!

但是当我将“LineA”更改为

const std::string greeting = "Hello, " + "Hello " + "!";

报错

HelloWorld.cpp:34:42: 错误: 'const char [8]' 类型的无效操作数 和'const char [6]'转二进制'operator+'
const std::string greeting = "Hello, " + "Hello" + "!";

为什么说无效的操作数类型?

【问题讨论】:

  • 因为“你好”不是 std::string
  • 但@Prakash 在第一种情况下也是“你好”,不是 std::string
  • @krishna 后一种情况没有 std::string 对象来评估 + 运算符..您正在尝试添加字符数组..
  • 那么您是说要评估必须至少有一个操作数字符串类型。这个案例呢@Prakash "Hello,"+"World"+name;
  • 表达式从左到右求值。 "Hello,"+ "World" 被求值,然后它尝试添加名称.. 但由于 "Hello" 和 "World" 都是字符数组 operator + 无法求值 ...

标签: c++ arrays string addition c-strings


【解决方案1】:

std::operator+ 可以应用于 std::string 对象,但不能应用于 char[]..

“你好,”是一个字符数组。

您可以执行以下添加,

 std::string hello = "Hello ,";
 std::string greeting = hello + name ;

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 2015-01-11
    • 2017-07-24
    • 2021-12-10
    • 2012-05-07
    • 1970-01-01
    • 2023-03-21
    • 2015-06-09
    相关资源
    最近更新 更多