无需发送任何内容即可返回函数(Get return of a function without sending anything)

编程入门 行业动态 更新时间:2024-10-26 20:34:15
无需发送任何内容即可返回函数(Get return of a function without sending anything)

我有一个函数头:

double countThis(double counter);

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

double test = 10; countThis(test);

然后是功能:

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

在底部,我有一个最后一个函数,在这里我想得到double counted而不必做countThis(something) ,我只想从上一次调用返回在main中获得并获得值10(计数) )。

I have a function header:

double countThis(double counter);

Then, in my main I do this:

double test = 10; countThis(test);

Then comes the function:

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

On the bottom, I have one last function, and here I want to get double counted without having to do countThis(something), I just want to get the return from the previous call that was made in main and get the value 10 (counted).

最满意答案

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

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用于保存您传递给countThis的值。

One way to achieve this sort of persistence is to use a class and define an instance of that class:

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

At the point of use:

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

The instance c is used to persist the value that you pass to countThis.

更多推荐

本文发布于:2023-08-07 22:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466161.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   内容   return   function   sending

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!