c++ - 如何引用“timeElapsed”中存储的内容以在另一个函数中进行比较?
问题描述
基本上,我想以秒为单位获取存储在变量“timeElapsed”中的时间,并将其用于另一个函数中的比较,以允许我的程序根据时间输出不同的内容。但是,我完全不确定如何在另一个函数中引用该局部变量,并且全局变量将不起作用,因为“timeElapsed”依赖于我的 setTimer() 函数中的其他代码。
请帮助一个迷路的学生!
void setTimer() {
int timeElapsed = 0;
time_t beginTimer = time(NULL);
timeElapsed = difftime(time(NULL), beginTimer);
解决方案
您需要提供更多上下文才能帮助解决此特定问题,但您可以通过多种方式访问 timeElapsed。
如果要将值传递给要更改的设置计时器,则可以传递对指针的引用并在函数外部更改变量
void setTimer(int *input) {
int timeElapsed = 3;
time_t beginTimer = time(NULL);
timeElapsed = difftime(time(NULL), beginTimer);
*input= timeElapsed; // Changes the compare variable in main
}
int main(){
int compare = 5;
setTimer(&compare);
cout << compare; // This will now be the timeElapsed from setTimer
return 0;
}
这将改变你作为 0 传入的任何内容,因为
time_t beginTimer = time(NULL);
timeElapsed = difftime(time(NULL), beginTimer);
将使 timeElapsed 为 0,但如果您尝试访问函数范围之外的变量,您可以传入要访问的变量,或通过更改void setTimer()
为int setTimer()
并返回来返回值timeElapsed
推荐阅读
- javascript - 初始化前无法访问“X”
- javascript - 如何更改此代码,以便每次刷新浏览器时都不会删除
- apache-flink - Data Stream API 中的 Flink 迭代 - 缺点
- javascript - 查找数组中最接近的较小值
- javascript - 我的删除按钮功能有什么问题 - 反应
- python - Python tkinter 文本到边界问题
- android - 滚动已在 scichart android 中绘制的折线图时如何修复延迟
- javascript - 根据 ID 存在的特定性别数据拆分组合列表
- grails - 为什么类名长度为一时,生成的控制器中没有注入服务?
- python - 将每个元组与元组列表中的下一个元组合并