【问题标题】:How to make variables within a function accessible to the main function?如何使主函数可以访问函数中的变量?
【发布时间】:2013-05-29 12:57:28
【问题描述】:

下面有一些简单的代码,我无法正确运行。本质上,我有一个自定义函数Create(),它根据用户输入创建一个变体(点、线、圆)。然后我在主函数中调用这个函数,并尝试调用我在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;
    }
}

【问题讨论】:

    标签: c++ function boost compiler-errors


    【解决方案1】:

    需要存储返回值:

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

    您不能访问该范围之外的范围(在本例中为 if/else 语句)的本地值。您可以从正在执行的函数返回值,您只需要存储该值即可使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2019-10-29
      相关资源
      最近更新 更多