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

I ran into a problem in my C ++ code.

I have a StateValue union:

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

and struct StateItem

 struct StateItem { LampState state; StateValue value; }; 

I have a method that goes through a StateItem 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 of Hue I get the following compiler error:

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

I can not understand the problem here. Can any of you please help me?

+11
c ++
source share
4 answers

You are trying to call a member function on intValue , which is of type int . int not a type of class, therefore it has no member functions.

In C ++ 11 or later there is a convenient function std::to_string for converting int and other built-in types to std::string :

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

Historically, you would have to do with string streams:

 { std::stringstream ss; ss << st.value.intValue; result += ", \"hue\": " + ss.str(); } 
+11
source share

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

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

You call str() on a member variable of type int and what the compiler complains about.

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

 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); 
+3
source share

Your intvalue is not an object. It does not have member functions. You can use sprintf () or itoa () to convert it to a string.

0
source share

intValue is int , it has no methods.

0
source share

All Articles