Alex
Alex

Reputation: 610

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

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?

Upvotes: 23

Views: 176347

Answers (4)

ichramm
ichramm

Reputation: 6642

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

Upvotes: 4

Mike Seymour
Mike Seymour

Reputation: 254461

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

Upvotes: 21

user1196549
user1196549

Reputation:

intValue is an int, it has no methods.

Upvotes: 0

scraatz
scraatz

Reputation: 419

Your intvalue is no object. It has no member functions. You could use sprintf() or itoa() to convert it to a string.

Upvotes: 1

Related Questions