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

标签 c++ function boost compiler-errors

我在下面有一些简单的代码,但无法正确运行。本质上,我有一个自定义函数 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;
    }
}

最佳答案

您需要存储返回值:

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

 ....

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

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

关于c++ - 如何使主函数可以访问函数中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16814543/

相关文章:

c++ - boost::filesystem::create_directories();将文件夹添加到陌生位置

c++ - 枚举 objective-C 和 "<<"运算符

c++ - 将字符串写入长度超过 4095 个字符的文件

ios - 设置隐藏不工作

c++ - std::stack<boost::shared_ptr<T>> 的深拷贝

c++ - 为不可复制对象选择构造函数

c++ - 如果旧的 C++ 编译器没有实现 new 关键字,那么将它定义掉是错误的吗?

c++ - boost::asio 无法完全关闭 TCP 连接

c++ - 我应该如何实现一个在 C++ 中接受未知数量参数的数组构造函数?

javascript - 运行存储在变量中的 jQuery 函数