c++从其他函数访问变量
C++ accessing variable from other function
我正在尝试用qt creator制作数字猜谜游戏。我需要从另一个函数访问一个变量。我可以通过在变量的开头添加"self."在python上做到这一点,但我不能在c++上做到这一点。下面是我正在尝试做的一个示例:
void function1()
{
int i;
}
void function2()
{
I need to access i here.
}
可以使用指针、类或全局变量(我建议使用指针或类)
void f1(int *iPtr)
{
cout << "value= " <<*iPtr << endl;
}
void f2(int *iPtr)
{
*iPtr = *iPtr + 5; // access ( modify ) variable here
cout << "after addition = " << *iPtr << endl;
}
int main()
{
int i = 5;
int *iPtr;
iPtr = &i; // point pointer to location of i
f1(iPtr);
f2(iPtr);
// after f1() value of i == 5, after f2() value of i == 10
}
我相信在c++中类似的行为应该是成员变量。
如果你还没有,我建议你使用类。因此,在你的头文件中像这样定义它:
class MyClass {
public:
void function1();
void function2();
private:
int i;
};
如果你不使用c++类,那么你可以在头文件中定义"i",但这将使它在本质上是全局的。这可能不是最好的做法。
不可能从另一个函数访问变量,因为它们只存在于堆栈中,并且在函数退出时销毁。使用全局变量
您可以将i声明为全局变量,并在选择后为其分配随机数。这样,你仍然可以生成一个随机数,并在另一个函数中使用它。
int i;
void function1()
{
int randNum;
// get random number here
i = randNum;
}
void function2()
{
// do stuff with i here
}
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 通过按地址访问变量
- 通过 get-Method 访问变量在类外不起作用
- 是否可以使用指针访问变量以避免直接编辑变量?
- 我无法访问变量的值,即使我通过范围传递了它
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- (C++) 从另一个类访问变量时值无效
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 是否可以从字符串访问变量?
- 变量 z 无法从其他函数访问变量 x
- 如何在 C++ 中从 void 返回函数访问变量
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 在C 中本地声明隐藏的封闭范围(而非全局)中访问变量
- 从函数中删除动态内存分配,但无法访问变量
- 如何从派生类中的基类访问变量的值?
- 如何通过指针更快地访问变量,然后直接访问变量?
- 如何在公共类 c++ 中访问变量的值
- 从 Visual Studio 中的多个源文件访问变量
- 使用命名空间和模板类访问变量
- 从子对话框访问变量