C ++文字串连接 [英] C++ Literal String Concatenation

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

问题描述

我有一个关于C ++中字符串连接的问题。

  string str =ab+'c' 
cout<< str<< endl;

char ch ='c';
string str1 =ab;
string str2 = str1 + ch;
cout<< str2 < endl;

代码产生:

  ed SaveGraphicsState之前
abc

这行: string str =ab+'c';

解决方案

您对第一行的想法是正确的,这正是发生的事情。



没有任何默认 + 运算符对于字符串ab,所以发生的是编译器采用(作为C风格的字符串),并使用 * 指向文字的指针。然后它将你的字符字符'c'并将其提升为具有某个值的 int 。然后将此int添加到文字的地址并用作C字符串。因为你超出了为你的文字字符串分配的空间,结果是未定义的,它只是从结果地址打印出来的字符,直到找到一个null。



如果你想要在一个镜头中创建字符串,可以帮助编译器找出你想要转换为 string 先用转换: std :: string str = std :: string(ab)+'c'; 。或者(如在单独的注释中看到的)使用级联执行它可能执行或可能不执行更好。使用在你的情况下更清楚的: std :: string str =ab;在第二种情况下,您已经创建了一个字符串 c $ c>和 string 有一个重载的运算符+ ,这是直观的连接。


I have a question about string concatenation in C++.

string str = "ab" + 'c';
cout << str << endl;

char ch = 'c';
string str1 = "ab";
string str2 = str1 + ch;
cout << str2 << endl;

The code produces:

ed before SaveGraphicsState
abc

Can someone explain the processing of this line: string str = "ab" + 'c'; ?

解决方案

Your thought regarding the first line is correct, that's precisely what's happening.

There isn't any default + operator for literal strings like "ab" so what happens is the compiler takes that (as a C-style string) and uses the const char* pointer that points to the literal. It then takes your literal character 'c' and promotes it to int with some value. This int is then added to the address of the literal and used as a C-string. Since you've exceeded the space allocated for your literal string, the results are undefined and it just printed out characters from the resulting address until it found a null.

If you want to create the string in one shot, you can help the compiler figure out that you wanted to convert to string first with a cast: std::string str = std::string("ab") + 'c';. Alternately (as seen in a separate comment) do it with concatenation which may or may not perform better. Use whichever seems clearer in your case: std::string str = "ab"; str += 'c';.

In the second case, you have already created a string and string has an overloaded operator+ that does the intuitive concatenation.

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

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