【问题标题】:C++ Member Reference base type 'int' is not a structure or unionC++ 成员引用基类型“int”不是结构或联合
【发布时间】:2014-01-27 17:36:27
【问题描述】:

我的 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 没有 str() 函数。它甚至不是一堂课。
  • 请注意,C++11 的新功能是能够在联合中使用非 pod 类型(如 std::string),因此如果您尝试使用不支持 C+ 的旧编译器进行编译+11 然后你会得到一个错误。
  • 至于你的问题,你不妨看看函数std::to_string
  • 编译器也会给出这个错误信息,如果你写了这样的东西:A a; int a = a.FunctionThatReturnsInt();

标签: c++


【解决方案1】:

您正在尝试调用 intValue 上的成员函数,该成员函数的类型为 intint 不是类类型,所以没有成员函数。

在 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();
}

【讨论】:

    【解决方案2】:

    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);
    

    【讨论】:

      【解决方案3】:

      您的 intvalue 不是对象。它没有成员函数。您可以使用 sprintf() 或 itoa() 将其转换为字符串。

      【讨论】:

      • 在 C++ 中,int 的实例是一个对象。
      • 标准(c++11)方式是使用std::to_string()
      【解决方案4】:

      intValue 是一个int,它没有方法。

      【讨论】:

        猜你喜欢
        • 2012-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 2021-03-07
        • 1970-01-01
        • 2013-12-11
        相关资源
        最近更新 更多