Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I'm running into a Problem in my C++ Code.

I have a union StateValue:

union StateValue
{
    int intValue;
    std::string value;
};

and a struct StateItem

struct StateItem
{
    LampState state;
    StateValue value;
};

I have a method which goes through a vector of type 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;
    }
}

In the case Hue I get the following Compiler error:

Member reference base type 'int' is not a structure or union

I can´t understand the problem here. Can anyone of you please help me?

like image 609
Alex Avatar asked Jan 27 '14 17:01

Alex


Video Answer


2 Answers

You're trying to call a member function on intValue, which has type int. int isn't a class type, so has no member functions.

In C++11 or later, there's a handy std::to_string function to convert int and other built-in types to std::string:

result += ", \"hue\": " + std::to_string(st.value.intValue);

Historically, you'd have to mess around with string streams:

{
    std::stringstream ss;
    ss << st.value.intValue;
    result += ", \"hue\": " + ss.str();
}
like image 180
Mike Seymour Avatar answered Sep 18 '22 04:09

Mike Seymour


Member reference base type 'int' is not a structure or union

int is a primitive type, it has no methods nor properties.

You are invoking str() on a member variable of type int and that's what the compiler is complaining about.

Integers cannot be implicitly converted to string, but you can used std::to_string() in C++11, lexical_cast from boost, or the old-slow approach of the stringstream.

std::string to_string(int i) {
    std::stringstream ss;
    ss << i;
    return ss.str();
}

or

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

And change the line to:

result += std::string(", \"hue\": ") + to_string(st.value.intValue);
like image 40
JuanR Avatar answered Sep 18 '22 04:09

JuanR