[英]C++ Member Reference base type 'int' is not a structure or union
我在我的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
的情況下,我得到以下編譯器錯誤:
Member reference base type 'int' is not a structure or union
我不明白這里的問題。 你能有人幫我嗎?
您正在嘗試在intValue
上調用成員函數,其類型為int
。 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_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);
你的intvalue不是對象。 它沒有成員功能。 您可以使用sprintf()或itoa()將其轉換為字符串。
intValue
是一個int
,它沒有方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.