c++ - 添加字符串和文字 (C++)
问题描述
在 C++ Primer 一书中,我遇到了这样的说法:“当我们混合字符串和字符串或字符文字时,每个 + 运算符的至少一个操作数必须是字符串类型”
我注意到以下内容无效:
#include<string>
int main()
{
using std::string;
string welcome = "hello " + "world"; //example 1
string short_welcome = 'h' + 'w'; //example 2
return 0;
}
- 问题 1:为什么示例 1 会产生错误,因为两个操作数都是字符串文字?
- 问题2:为什么至少有一个操作数必须是字符串?
- 问题3:为什么示例2也会产生错误?
我只是想了解幕后发生的事情。
解决方案
您只能为用户定义的类型(例如 class )重载运算符std::string
。
所以这些基本类型的运算符
"hello " + "world"
'h' + 'w'
不能超载。
在第一个表达式中,字符串文字被转换为指向它们的第一个元素的指针。但是,二元运算符 + 没有为指针定义。
在第二个表达式中,字符文字被转换为整数,结果是一个整数。然而,类 std::string 没有接受整数的隐式构造函数。
你可以写例如
string welcome = std::string( "hello " ) + "world";
或者
string welcome = "hello " + std::string( "world" );
或者
string short_welcome( 1, 'h' );
short_welcome += 'w';
推荐阅读
- sql - 有效查询,失败查看
- python - 如何使用嵌套的字典匹配簿数据遍历 JSON 列表?
- sql-server - 具有最小值和最大值的 SQL Server 子查询
- reporting-services - 如何将所有钻取组放在同一行 - SSRS 报告
- c++ - 必须实现 C++ 中的虚函数?
- python - 如何使用 argparse IP 地址和社区字符串?
- php - 在 datetimepicker 输入 uisng MySQL、PHP 和 PDO 上过滤数据库中的数据
- java - 如何使用 xpath 表达式从项目型号中刮取文本 64076
- javascript - 与混合应用程序一起使用时,Angularjs 摘要正在进行错误
- arrays - 我如何获得这种类型的 obj [{...}, {...}] 而不是这个 [] 数组?