首页 > 解决方案 > 添加字符串和文字 (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;
}

我只是想了解幕后发生的事情。

标签: c++stringoperator-overloadinguser-defined-types

解决方案


您只能为用户定义的类型(例如 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';

推荐阅读