如何使函数中的变量可以被主函数访问
How to make variables within a function accessible to the main function?
我有一些简单的代码下面,我有问题得到正确运行。从本质上讲,我有一个自定义函数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
语句)。你可以从你正在做的函数中返回值,你只需要存储该值以使用它。
相关文章:
- 使用不带参数的函数访问结构元素
- 删除目录函数访问被拒绝
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 我想要一个具有子函数的函数访问相同的命名函数,而不使用它取决于其子类的类
- 有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?
- 如何在C++通过公共函数访问私有函数成员?
- 限制variadic模板类中的构造函数访问
- 从析构函数访问模板类构造函数的参数,可以吗?
- 变量 z 无法从其他函数访问变量 x
- 从静态成员函数访问私有非静态类变量 - C++
- 如何在 C++ 中从 void 返回函数访问变量
- 在类中使用映射并通过其他类的 get() 和 set() 函数访问值
- 无法从另一个函数访问文件范围变量的内容
- 是否可以从 C++ 中的构造函数访问对象名称?
- 使用C 中的共享_ptr从公共静态成员函数访问私有构造函数
- 使用静态成员函数访问静态数据成员
- 为什么我们可以从 C++ 中的成员函数访问 non_member 函数
- 如何使用 c++ 中的函数访问全局变量?
- 如何从 C++ 中的主函数访问类中的私有构造函数?