字符串文字和字符文字可以连接吗? [英] Can a string literal and a character literal be concatenated?

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

问题描述

为什么 name 在以下C ++代码中出现异常?

  string name =ab+'c'; 

等效代码在Java / C#中的行为如何?

解决方案

尝试

  std :: string name =ab C; 

  std :: string name = std :: string(ab)+ c; 

在C ++中,ab不是 std :: string ,而是指向字符串的指针。当你向一个指针添加一个整数值时,你会得到一个新的指针,指向下面的字符串:

  char * foo = 012345678910121416182022242628303234; 
std :: string name = foo +'';

name 设置为3234因为''的整数值为32,并且超过foo开头的32个字符是字符串结尾之前的四个字符。如果字符串较短,您将尝试在未定义的内存区域中访问某些内容。



解决方法是从字符数组中生成一个std: 。 std:strings可以按照预期将字符附加到它们:

  std :: string foo =012345678910121416182022242628303234; 
std :: string name = foo +'';

名称设置为012345678910121416182022242628303234 / p>

Why does name misbehave in the following C++ code?

string name =  "ab"+'c';

How would the equivalent code behave in Java/C#?

解决方案

Try

std::string name = "ab" "c";

or

std::string name = std::string("ab") + c;

In C++, "ab" is not a std::string, but rather a pointer to a string of chars. When you add an integral value to a pointer, you get a new pointer that points farther down the string:

char *foo = "012345678910121416182022242628303234";
std::string name = foo + ' '; 

name gets set to "3234", since the integer value of ' ' is 32 and 32 characters past the begining of foo is four characters before the end of the string. If the string was shorter, you'd be trying to access something in undefined memory territory.

The solution to this is to make a std:string out of the character array. std:strings let you append characters to them as expected:

std::string foo = "012345678910121416182022242628303234";
std::string name = foo + ' '; 

name gets set to "012345678910121416182022242628303234 "

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

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