C++ 成员引用基类型'int'不是结构或联合
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
我会收到以下编译器错误:
会员参考基础类型'int'不是结构或联合
我在这里无法理解问题。你们中的任何人都可以帮我吗?
您正在尝试调用具有int
类型的intValue
上的成员函数。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);
您的插入不是对象。它没有成员功能。您可以使用sprintf()或itoa()将其转换为字符串。
intValue
是int
,它没有方法。
相关文章:
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 编译器指出结构和 int 说明的错误 2059
- C++ std::vector<int> 体系结构的未定义符号 x86_64:
- 对结构int成员进行排序
- for 循环说 - 错误 成员引用基类型"int [13]"不是结构或联合
- 为什么我不能将 int 分配给结构成员的联合成员?
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 将 int 映射到 C++ 中的向量结构
- STL 对priority_queue<int、结构>错误
- 如何将来自文本文件的数据读取到结构的int阵列中
- 错误:成员引用基类型"uint32_t"(也称为"无符号 INT")不是结构或联合
- 如何从输入中定义的"external" int 定义结构中的数组大小
- 结构C++可以用 0 初始化,但不能用另一个 int 初始化
- C++ 如何从指向结构的指针将 PTR 返回到 int
- 在 UDP 套接字上发送结构、浮点数和 int C++
- 声明 Windows API 结构 (DCB) 的对象 - 错误 C4430:缺少类型说明符 - 假定为 int
- 如何在另一个结构 arrya 中的一个结构中初始化一个 int 数组
- 是一个包含两个INT(只有两个INT)的结构,保证是大小(INT)的两倍
- 带有两个INT列表的结构将减少为一个INT
- 是否有任何环境会导致"int"结构填充?