2013-06-04 47 views
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; 
} 

回答

8

得到一個編譯器錯誤你的函數應該像下面:

boost::optional<Myclass> func(int a) 
{ 
    boost::optional<Myclass> value; 
    if(a == 0) 
     value = {200}; 

    return value; 
} 

你可以通過投射到01來檢查它:

boost::optional<Myclass> v = func(42); 
if(v) 
    std::cout << v -> a << std::endl; 
else 
    std::cout << "Uninitilized" << std::endl; 

不是它會是值 - >一個= 200

不,事實並非如此。從Boost.Optional.Docs

T const* optional<T (not a ref)>::operator ->() const ; 

T* optional<T (not a ref)>::operator ->() ; 
  • 要求:*這是初始化
  • 返回:指向包含值的指針。
  • 拋出:無。
  • 注:需求通過BOOST_ASSERT()斷言。

而在operator->定義:

pointer_const_type operator->() const 
{ 
    BOOST_ASSERT(this->is_initialized()); 
    return this->get_ptr_impl(); 
} 

如果對象未初始化,斷言將失敗。當我們寫

value = {200}; 

我們初始化值爲Myclass{200}


。注意,value = {200}需要初始化列表支持(C++ 11功能)。與int

Myclass c; 
c.a = 200; 
value = c; 

或提供構造函數Myclass作爲參數:如果你的編譯器不支持它,你可以使用它像這樣

Myclass(int a_): a(a_) 
{ 

} 

然後,你可以只寫

value = 200; 
+0

我對'value = {200}'感到困惑'是不是'value-> a = 200'? – MistyD

+0

@MistyD,看看編輯。 – soon

+0

感謝您的編輯。但是'value = {200};'在編譯錯誤C2143時出現編譯錯誤:語法錯誤:缺少';'之前'{'' – MistyD