首页 > 解决方案 > 如何引用“timeElapsed”中存储的内容以在另一个函数中进行比较?

问题描述

基本上,我想以秒为单位获取存储在变量“timeElapsed”中的时间,并将其用于另一个函数中的比较,以允许我的程序根据时间输出不同的内容。但是,我完全不确定如何在另一个函数中引用该局部变量,并且全局变量将不起作用,因为“timeElapsed”依赖于我的 setTimer() 函数中的其他代码。

请帮助一个迷路的学生!

void setTimer() {
    int timeElapsed = 0;

    time_t beginTimer = time(NULL);

    timeElapsed = difftime(time(NULL), beginTimer);

标签: c++

解决方案


您需要提供更多上下文才能帮助解决此特定问题,但您可以通过多种方式访问​​ 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


推荐阅读