6

オブジェクトまたは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;
}

アップデート:

これは私の新しいコードで、コンパイル エラーが発生します。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;
}
4

1 に答える 1