在不发送任何内容的情况下获取功能的返回

Get return of a function without sending anything

本文关键字:情况下 获取 功能 返回 任何内      更新时间:2023-10-16

我有一个功能标头:

double countThis(double counter);

然后,在我的主要中,我这样做:

double test = 10;
countThis(test);

随后出现了函数:

double countThis(double counter) {
    double counted = counter;
    return counted;
}

在底部,我有一个最后一个功能,在这里我想获得double counted而无需进行countThis(something),我只想从MAIN进行的上一个呼叫中获取返回并获得值10(计数)。

实现这种持久性的一种方法是使用类并定义该类的实例

struct Counter
{
    double counted;
    double countThis(double counter)
    {
        return counted = counter; // assign counter to counted, and return that value.
    }
};

在使用点:

int main()
{
    Counter c;
    c.countThis(10);
    // c.counted contains the last value sent to countThis, in this case, 10
}

实例 c用于 persist 您传递给 countThis的值。

执行此操作:

double test = 10;
double ret;
ret = countThis(test);
// Now the value returned by countThis is in ret

您可以使用全局变量。(双计数)和函数

double countThis(double counter) {
   counted = counter;
    return counted;
}

将另一个函数定义为仅返回计数

double count() {
    return counted;
}

但是,我建议您创建一个结构并在其上制作getter和setter。

为什么不将值复制到double的新实例?

示例:

double test = 10;
countThis(test);
double something = test;