[英]C++ Member Reference base type 'int' is not a structure or union
我在我的C ++代码中遇到了问题。
我有一个联合StateValue
:
union StateValue
{
int intValue;
std::string value;
};
和一个结构StateItem
struct StateItem
{
LampState state;
StateValue value;
};
我有一个方法,它通过StateItem
类型的向量
for(int i = 0; i < stateItems.size(); i++)
{
StateItem &st = stateItems[i];
switch (st.state)
{
case Effect:
result += std::string(", \"effect\": ") + st.value.value;
break;
case Hue:
result += std::string(", \"hue\": ") + st.value.intValue.str();
break;
case On:
result += std::string(", \"on\": ") + std::string(st.value.value);
break;
default:
break;
}
}
在Hue
的情况下,我得到以下编译器错误:
Member reference base type 'int' is not a structure or union
我不明白这里的问题。 你能有人帮我吗?
您正在尝试在intValue
上调用成员函数,其类型为int
。 int
不是类类型,因此没有成员函数。
在C ++ 11或更高版本中,有一个方便的std::to_string
函数将int
和其他内置类型转换为std::string
:
result += ", \"hue\": " + std::to_string(st.value.intValue);
从历史上看,你不得不乱用字符串流:
{
std::stringstream ss;
ss << st.value.intValue;
result += ", \"hue\": " + ss.str();
}
Member reference base type 'int' is not a structure or union
int
是基本类型,它没有方法也没有属性。
您正在对int
类型的成员变量调用str()
,这是编译器抱怨的内容。
整数不能隐式转换为字符串,但你可以在C ++ 11中使用std::to_string()
,使用boost
lexical_cast
,或者使用stringstream
的旧 - 慢速方法。
std::string to_string(int i) {
std::stringstream ss;
ss << i;
return ss.str();
}
要么
template <
typename T
> std::string to_string_T(T val, const char *fmt ) {
char buff[20]; // enough for int and int64
int len = snprintf(buff, sizeof(buff), fmt, val);
return std::string(buff, len);
}
static inline std::string to_string(int val) {
return to_string_T(val, "%d");
}
并将行更改为:
result += std::string(", \"hue\": ") + to_string(st.value.intValue);
你的intvalue不是对象。 它没有成员功能。 您可以使用sprintf()或itoa()将其转换为字符串。
intValue
是一个int
,它没有方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.