如何使函数中的变量可以被主函数访问

How to make variables within a function accessible to the main function?

本文关键字:函数 访问 变量 何使      更新时间:2023-10-16

我有一些简单的代码下面,我有问题得到正确运行。从本质上讲,我有一个自定义函数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;
    }
}

您需要存储返回值:

 ShapeType retShapeType = Create() ;
 std::cout<<retShapeType<<std::endl;
 ....
 lnA = boost::get<Line>( retShapeType );

你不能访问作用域之外的局部值(在这个例子中是if/else语句)。你可以从你正在做的函数中返回值,你只需要存储该值以使用它。