尝试使用boost :: optional失败了

Mis*_*tyD 5 c++ boost-optional

我一直在尝试使用boost可选的函数来返回一个对象或null,我无法弄明白.这是我到目前为止所拥有的.任何有关如何解决此问题的建议将不胜感激.

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;
}
Run Code Online (Sandbox Code Playgroud)

更新:

这是我的新代码,我收到了编译错误 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;
}
Run Code Online (Sandbox Code Playgroud)

awe*_*oon 8

您的功能应如下所示:

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

    return value;
}
Run Code Online (Sandbox Code Playgroud)

你可以通过转换来检查它bool:

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

它不会是值 - > a = 200

不,不是.来自Boost.Optional.Docs:

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

T* optional<T (not a ref)>::operator ->() ;
Run Code Online (Sandbox Code Playgroud)
  • 要求:*已初始化.
  • 返回:指向包含值的指针.
  • 投掷:没什么.
  • 注意:要求通过BOOST_ASSERT()声明.

operator->定义中:

pointer_const_type operator->() const
{
    BOOST_ASSERT(this->is_initialized());
    return this->get_ptr_impl();
}
Run Code Online (Sandbox Code Playgroud)

如果未初始化object,则断言将失败.当我们写作

value = {200};
Run Code Online (Sandbox Code Playgroud)

我们初始化价值Myclass{200}.


注意,这value = {200}需要支持初始化列表(C++ 11功能).如果您的编译器不支持它,您可以像这样使用它:

Myclass c;
c.a = 200;
value = c;
Run Code Online (Sandbox Code Playgroud)

或者为Myclasswith 提供构造int函数:

Myclass(int a_): a(a_)
{

}
Run Code Online (Sandbox Code Playgroud)

然后你就可以写了

value = 200;
Run Code Online (Sandbox Code Playgroud)