C++ 成员引用基类型'int'不是结构或联合

C++ Member Reference base type 'int' is not a structure or union

本文关键字:结构 int 类型 引用 成员 C++ 基类      更新时间:2023-10-16

我正在遇到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_caststringstream的旧慢方法。

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()将其转换为字符串。

intValueint,它没有方法。