2013-05-29 70 views
0

我有一些簡單的代碼,我無法正確運行。基本上,我有一個自定義功能Create(),根據用戶輸入創建一個變體(Point,Line,Circle)。然後我在主函數中調用這個函數,並試圖調用我在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; 
    } 
} 

回答

2

您需要存儲的返回值:

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

.... 

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

您不能訪問該範圍之外是本地的範圍(在這種情況下if/else語句)值。您可以從您正在執行的函數中返回值,只需存儲該值即可使用它。

相關問題