C++ 错误——表达式必须具有整数或枚举类型——从带有连接的字符串中获取它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22753328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ error -- expression must have integral or enum type -- getting this from a string with concatenation?
提问by SuperCow
C++ error expression must have integral or enum typegetting this from a string with concatenation?
C++ 错误表达式必须具有整数或枚举类型,从带有连接的字符串中获取它?
So in the toString()
of a class in C++ I have the code:
所以在toString()
C++ 的一个类中,我有代码:
string bags = "Check in " + getBags() + " bags";
I thought I could declare a string like this? (I'm coming from a Java background and trying to learn C++). The bags
is underlined in Visual Studio though and the problem is:
我以为我可以声明这样的字符串?(我来自 Java 背景并试图学习 C++)。将bags
在Visual Studio强调,虽然和问题是:
expression must have integral or enum type.
表达式必须具有整数或枚举类型。
getBags()
just returns an int
.
getBags()
只返回一个int
.
Another example where this happens is with:
发生这种情况的另一个例子是:
string totalPrice = "Grand Total: " + getTotalPrice();
getTotalPrice()
returns a float
and is what is underlined with the error.
getTotalPrice()
返回 afloat
并且是错误下划线的内容。
But then if I put in a line like:
但是,如果我输入如下一行:
string blah = getBags() + "blah";
No errors.
没有错误。
What am I not understanding here?
我在这里不明白什么?
采纳答案by Ferruccio
"Check in "
is actually a const char *
.
Adding getBags()
(an int
) to it yields another const char*
. The compiler error is generated because you cannot add two pointers.
"Check in "
实际上是一个const char *
. 将getBags()
(an int
)添加到它会产生另一个const char*
。生成编译器错误是因为您无法添加两个指针。
You need to convert both "Check in "
and getBags()
to strings before concatenating them:
需要转换都"Check in "
和getBags()
以串联它们之前的字符串:
string bags = std::string("Check in ") + std::to_string(getBags()) + " bags";
" bags"
will be implicitly converted to a string
.
" bags"
将被隐式转换为 a string
。
回答by SHR
when using + to append strings the first element must have operator+, const char* doesn't have it.
当使用 + 附加字符串时,第一个元素必须有 operator+,而 const char* 没有。
therefore you should to make a string from it:
因此,您应该从中制作一个字符串:
string bags = string("Check in ") + getBags() + " bags";
or to do it in to steps:
或按以下步骤操作:
string bags = string("Check in ") + getBags() + " bags";
EDIT:More problem is the int returned from the method, for some reason, string doesn't have operator+ for int.
编辑:更多的问题是从方法返回的 int,出于某种原因,字符串没有用于 int 的 operator+。
So you better use stringstream like this:
所以你最好像这样使用 stringstream:
#include <sstream>
....
ostringstream s;
s<<"Check in " << getBags() << " bags";
string bags = s.str();
回答by Lee Thomas
Try std::to_string(getBags())
. You can only concatenate strings with strings.
试试std::to_string(getBags())
。您只能将字符串与字符串连接起来。