可以将字符串文字和字符文字被串联? [英] Can a string literal and a character literal be concatenated?

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

问题描述

为什么名称胡作非为下面的C ++代码?

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

string name =  "ab"+'c';



如何将同等代码的行为中的Java / C#?

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

推荐答案

尝试

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

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

在C ++中,AB是不是的std :: string的,而是一个指向字符的字符串。当您添加一个积分值的指针,你会得到一个新的指针越向下指的字符串:

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 + ' ';



名称被设置为3234,因为整数值'是32和32个字符过去美孚的开头是字符串结束前四个字符。如果字符串较短,你会试图访问未定义的内存境内东西

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.

解决这个问题的解决方案是让一个std:串出的字符数组。 STD:字符串让你追加的字符他们预期:

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 + ' ';



名称被设置为012345678910121416182022242628303234

name gets set to "012345678910121416182022242628303234 "

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

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