Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使主函数可以访问函数中的变量?_C++_Function_Boost_Compiler Errors - Fatal编程技术网

C++ 如何使主函数可以访问函数中的变量?

C++ 如何使主函数可以访问函数中的变量?,c++,function,boost,compiler-errors,C++,Function,Boost,Compiler Errors,下面我有一些简单的代码,我无法正确运行。本质上,我有一个自定义函数Create(),它根据用户的输入创建变量(点、线、圆)。然后我在main函数中调用这个函数,并尝试调用我在Create()中创建的变量。这显然行不通。如何解决这个问题 using boost::variant; //Using declaration for readability purposes typedef variant<Point, Line, Circle> ShapeType; //typedef f

下面我有一些简单的代码,我无法正确运行。本质上,我有一个自定义函数
Create()
,它根据用户的输入创建变量(点、线、圆)。然后我在main函数中调用这个函数,并尝试调用我在
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;
    }
}
使用boost::variant//为可读性目的使用声明
typedef变体形状类型//ShapeType的typedef
ShapeType创建()
{
整数形状枚举器;
Coutshapper;
if(shapeEnumber==1)
{
ShapeType mytype=Point();
返回mytype;
}
else if(ShapeEnumber==2)
{
ShapeType mytype=Line();
返回mytype;
}
else if(ShapeEnumber==3)
{
ShapeType mytype=Circle();
返回mytype;
}
其他的
{
投掷-1;
}
}
int main()
{
尝试
{

cout您需要存储返回值:

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

 ....

 lnA = boost::get<Line>( retShapeType );
ShapeType retShapeType=Create();
标准::cout