5
我一直試圖使用boost可選函數,可以返回一個對象或null,我不能弄明白。這是我到目前爲止。任何建議如何解決這個問題,將不勝感激。失敗嘗試使用boost ::可選
class Myclass
{
public:
int a;
};
boost::optional<Myclass> func(int a) //This could either return MyClass or a null
{
boost::optional<Myclass> value;
if(a==0)
{
//return an object
boost::optional<Myclass> value;
value->a = 200;
}
else
{
return NULL;
}
return value;
}
int main(int argc, char **argv)
{
boost::optional<Myclass> v = func(0);
//How do I check if its a NULL or an object
return 0;
}
更新:
這是我的新的代碼,我在value = {200};
class Myclass
{
public:
int a;
};
boost::optional<Myclass> func(int a)
{
boost::optional<Myclass> value;
if(a == 0)
value = {200};
return value;
}
int main(int argc, char **argv)
{
boost::optional<Myclass> v = func(0);
if(v)
std::cout << v -> a << std::endl;
else
std::cout << "Uninitilized" << std::endl;
std::cin.get();
return 0;
}
我對'value = {200}'感到困惑'是不是'value-> a = 200'? – MistyD
@MistyD,看看編輯。 – soon
感謝您的編輯。但是'value = {200};'在編譯錯誤C2143時出現編譯錯誤:語法錯誤:缺少';'之前'{'' – MistyD