简体   繁体   English

C++ 将字符串文字添加到字符文字

[英]C++ Adding String Literal to Char Literal

I have a question about string concatenation in C++.我对 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';有人可以解释这一行的处理: 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.对于像"ab"这样的文字字符串,没有任何默认的+运算符,所以编译器会采用它(作为 C 风格的字符串)并使用指向文字的const char*指针。 It then takes your literal character 'c' and promotes it to int with some value.然后它将您的文字字符'c'提升为具有某些值的int This int is then added to the address of the literal and used as a C-string.然后将此 int 添加到文字的地址并用作 C 字符串。 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';如果您想一次性创建字符串,您可以帮助编译器确定您想先通过强制转换转换为stringstd::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';使用在您的情况下看起来更清晰的任何一个: std::string str = "ab"; str += 'c'; 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.在第二种情况下,您已经创建了一个string ,并且string有一个重载的operator+来进行直观的连接。

string str = "ab" + 'c';

string literals cannot be concatenated like that.字符串文字不能像那样连接。 "ab" is an array of character, which decays into pointer (in this context) and you're adding 'c' which is an integral to the pointer. "ab"是一个字符数组,它衰减为指针(在这种情况下),并且您正在添加'c' ,它是指针的一个组成部分。 So the pointer is advancing by the ascii value of 'c' .所以指针前进了'c'的 ascii 值。

That is, the above code is equivalent to this:也就是说,上面的代码等价于:

char char * s= "ab";
string str = &s['c']; //the ascii value of 'c' acts like an index to the array. 

I'm sure that isn't what you intended.我敢肯定这不是你想要的。 In fact, it invokes undefined behavior, because &s['c'] refers to a memory region which might not be in the process's address space.事实上,它调用了未定义的行为,因为&s['c']引用的内存区域可能不在进程的地址空间中。


The short form of what you actually want to do (ie concatenation), is this:您实际想要做的事情的简短形式(即连接)是这样的:

string str = string("ab") + "c";

您的猜测是正确的,除了字符串文字不在堆栈上,它位于内存中特定于工具链的位置,通常位于只读部分。

Operator overloading only works where at least one of the overloaded operator's parameters is a user-defined type (ie a class instance), so the + operator cannot be overloaded to add a character string and a character.运算符重载仅适用于至少一个重载运算符的参数是用户定义类型(即类实例)的情况,因此无法重载 + 运算符以添加字符串和字符。 and do something sensible.并做一些明智的事情。 At best, you will get pointer arithmetic being performed - almost certainly not what you want.充其量,您将执行指针算术 - 几乎可以肯定不是您想要的。 The usual workround for this is an explicit conversion:通常的解决方法是显式转换:

string s = string( "foo" ) + "bar";    // s will contain "foobar"
"ab"

Is a C-string.是一个 C 字符串。

'c'

Is a character.是一个人物。

Try:尝试:

string str = string("ab") + "c";

If you want to make it simpler, there's always:如果你想让它更简单,总是有:

string str = "ab";
str += 'c';

Alternatively, you can use std::stringstream :或者,您可以使用std::stringstream

stringstream ss;
ss << "ab" << 'c';

This is build into C++:这是内置到 C++ 中的:

#include <iostream>
#include <string>

int main()
{
    std::string s("Stand back! I've got jimmies!" "DDD");
    std::cout << "Stand back! I've got jimmies!" "DDD";
}

output:输出:

Stand back! I've got jimmies!DDD

"ab" is a const char * . "ab"是一个const char * 'c' is a char . 'c'是一个char My guess is that 'c' is converted to an integer, said integer is added to the address of "ab" , and the resulting pointer is passed to std::string 's constructor.我的猜测是'c'被转换为一个整数,所述整数被添加到"ab"的地址,并将结果指针传递给std::string的构造函数。 You're lucky it's not miserably crashing.你很幸运,它没有惨遭崩溃。

See the other answers for how to do the concatenation properly.请参阅其他答案以了解如何正确进行连接。

I think string str = "ab" + 'c';我认为string str = "ab" + 'c'; works something like:像这样工作:

string tmp = stirng("ab"); // implicit conversion
tmp = tmp + 'c'; // uses overloaded + operator
str = tmp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM