C++ 中的串联运算符?
我有一个应用程序,我需要在变量中组合字符串,如下所示:
int int_arr[4];
int_arr[1] = 123;
int_arr[2] = 456;
int_arr[3] = 789;
int_arr[4] = 10;
std::string _string = "Text " + int_arr[1] + " Text " + int_arr[2] + " Text " + int_arr[3] + " Text " + int_arr[4];
它给了我编译错误
Error C2210: '+' Operator cannot add pointers" on the second string of the expression.
据我所知,我正在组合字符串文字和整数,而不是指针。
我应该使用另一个串联运算符吗?或者这个表达完全错误,应该找出另一种方法来实现这一点?
顺便说一句,我正在使用 Visual Studio 2010
I have an application in which I need to combine strings within a variable like so:
int int_arr[4];
int_arr[1] = 123;
int_arr[2] = 456;
int_arr[3] = 789;
int_arr[4] = 10;
std::string _string = "Text " + int_arr[1] + " Text " + int_arr[2] + " Text " + int_arr[3] + " Text " + int_arr[4];
It gives me the compile error
Error C2210: '+' Operator cannot add pointers" on the second string of the expression.
As far as I can tell I am combining string literals and integers, not pointers.
Is there another concatenation operator that I should be using? Or is the expression just completely wrong and should figure out another way to implement this?
BTW I am using Visual Studio 2010
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 Java 中执行此操作,因为它在每个部分上自动使用
toString()
方法。如果您想在 C++ 中以相同的方式执行此操作,则必须将这些整数显式转换为字符串才能使其工作。
比如:
当然,你可以直接使用:
这要容易得多。
You can do this in Java since it uses the
toString()
method automatically on each part.If you want to do it the same way in C++, you'll have to explicitly convert those integer to strings in order for this to work.
Something like:
Of course, you can just use:
which is a lot easier.
在此上下文中,字符串文字成为指针。不是
std::string
。 (好吧,为了学究气地正确,字符串文字是字符数组,但数组的名称具有到指针的隐式转换。+
运算符的一种预定义形式采用指针左参数和整数右参数,这是最好的匹配,因此根据 C++ 重载规则,用户定义的转换不能优先于此内置转换。)。你应该学习一本好的 C++ 书籍,我们这里有一个列表所以。
A string literal becomes a pointer in this context. Not a
std::string
. (Well, to be pedantically correct, string literals are character arrays, but the name of an array has an implicit conversion to a pointer. One predefined form of the+
operator takes a pointer left-argument and an integral right argument, which is the best match, so the implicit conversion takes place here. No user-defined conversion can ever take precedence over this built-in conversion, according to the C++ overloading rules.).You should study a good C++ book, we have a list here on SO.
字符串文字是返回指针 const char* 的表达式。
A string literal is an expression returning a pointer
const char*
.C 和 C++ 都不允许 const char * 和 int 的串联。即使 C++ 的
std::string
也不会连接整数。使用流代替:Neither C nor C++ allow concatenation of
const char *
andint
. Even C++'sstd::string
, doesn't concatenate integers. Use streams instead: