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;
}
}