使用“+”连接字符串。在c ++ [英] concatenating strings using "+" in c++

查看:218
本文介绍了使用“+”连接字符串。在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,我指的是Accelerated C ++。在尝试其中一个练习问题时说:

I am a novice in C++ and i am referring Accelerated C++. While trying one of its exercise questions which says:

Are the following definitions valid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;

执行的程序我得到一个错误:

When i tried & executed the program i am getting an error as:


二进制运算符的类型的无效操作符+。

invalid operands of types to binary operator +.

但是下面的代码完全正常:

But the following code works perfectly fine:

const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";

我不清楚它的执行!为什么这种连接在第一种情况下不工作?

I am not clear with its execution! why this concatenation in the first case not working?

谢谢!我使用DEV C ++。

Thanks!I am using DEV C++.

推荐答案

第一个表达式

"Hello" + ", world"

编译器需要找到一个合适的函数,如 operator +(const char *,const char *)

the compiler needs to find a suitable function such as operator+(const char *, const char *). No such function exists, so it cannot compile.

相反,

hello + ", world"

正在寻找一个匹配的运算符+(const std :: string& const char *),并且重载存在 std :: string )。

is looking for one matching operator+(const std::string&, const char*), and that overload does exist (it is provided by std::string).

请注意,即使您自己的重载:

Note that you even if you could write your own overload:

std::string operator+ (const char *left, const char *right)
{
    return std::string(left) + right;
}

(不能像Praetorian指出的那样)是一个好主意。

(and you can't, as Praetorian points out) it wouldn't be a good idea.

首先,使用原始参数,你会失去ADL(即,如果标准库将操作符放在命名空间 std

Firstly, with primitive arguments, you'd lose ADL (ie, if the standard library put the operator in namespace std, it wouldn't normally be visible outside).

其次,如果您拥有自己的其他图书馆字符串表示(例如,诸如RogueWave或Qt等之类的pre-STL内容),他们同样可以为 字符串类型提供重载,编译器将无法在他们之间选择。

Secondly, if you have other libraries with their own string representations (eg. pre-STL stuff like RogueWave, or Qt, etc. etc.) they'd be equally justified in providing an overload for their string type, and the compiler would have no way to choose between them.

这篇关于使用“+”连接字符串。在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆