C ++错误-表达式必须具有整数或枚举类型-从具有串联的字符串中获取此类型? [英] C++ error -- expression must have integral or enum type -- getting this from a string with concatenation?
问题描述
C ++错误表达式必须具有整数或枚举类型,该字符串是从带有串联的字符串中获取的吗?
C++ error expression must have integral or enum type getting this from a string with concatenation?
因此在C ++中某个类的 toString()
中,我有以下代码:
So in the toString()
of a class in C++ I have the code:
string bags = "Check in " + getBags() + " bags";
我以为可以声明这样的字符串?(我来自Java背景,试图学习C ++).但是,在Visual Studio中对 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:
表达式必须具有整数或枚举类型.
expression must have integral or enum type.
getBags()
仅返回 int
.
发生这种情况的另一个示例是:
Another example where this happens is with:
string totalPrice = "Grand Total: " + getTotalPrice();
getTotalPrice()
返回 float
,并且带有错误的下划线是.
getTotalPrice()
returns a float
and is what is underlined with the error.
但是如果我把这样的行放进去:
But then if I put in a line like:
string blah = getBags() + "blah";
没有错误.
我在这里不明白什么?
推荐答案
签入"
实际上是 const char *
.向其添加 getBags()
(一种 int
)会生成另一个 const char *
.生成编译器错误是因为无法添加两个指针.
"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.
在连接它们之前,您需要将签入"
和 getBags()
都转换为字符串:
You need to convert both "Check in "
and getBags()
to strings before concatenating them:
string bags = std::string("Check in ") + std::to_string(getBags()) + " bags";
袋子"
将隐式转换为 string
.
这篇关于C ++错误-表达式必须具有整数或枚举类型-从具有串联的字符串中获取此类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!