0

以下に、正しく実行できない簡単なコードをいくつか示します。基本的にCreate()、ユーザーの入力に応じてバリアント (ポイント、ライン、サークル) を作成するカスタム関数があります。次に、メイン関数でこの関数を呼び出し、.NET で作成したバリアントを呼び出そうとしますCreate()。これは明らかに機能しません。これはどのように修正できますか?

using boost::variant; //Using declaration for readability purposes
typedef variant<Point, Line, Circle> ShapeType; //typedef for ShapeType

ShapeType Create()
{
    int shapenumber;

    cout<<"Variant Shape Creator - enter '1' for Point, '2' for Line, or '3' for Circle: ";
    cin>>shapenumber;

    if (shapenumber == 1)
    {
        ShapeType mytype = Point();
        return mytype;
    }

    else if (shapenumber == 2)
    {
        ShapeType mytype = Line();
        return mytype;
    }

    else if (shapenumber == 3)
    {
        ShapeType mytype = Circle();
        return mytype;
    }

    else
    {
        throw -1;
    }
}

int main()
{
    try
    {
        cout<<Create()<<endl;

        Line lnA;
        lnA = boost::get<Line>(mytype); //Error: identified 'mytype' is undefined
    }

    catch (int)
    {
        cout<<"Error! Does Not Compute!!!"<<endl;
    }

    catch (boost::bad_get& err)
    {
        cout<<"Error: "<<err.what()<<endl;
    }
}
4

1 に答える 1

2

戻り値を保存する必要があります。

 ShapeType retShapeType = Create() ;
 std::cout<<retShapeType<<std::endl;

 ....

 lnA = boost::get<Line>( retShapeType );

if/elseスコープ外のスコープ (この場合はステートメント) に対してローカルな値にアクセスすることはできません。実行している関数から値を返すことができます。その値を使用するには、その値を保存する必要があります。

于 2013-05-29T13:01:16.030 に答える