从虚函数返回值 [英] Returning value from Void Function

查看:533
本文介绍了从虚函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从void函数中获取价值?
请举个例子.
谢谢.

How is it possible to get value from void function?
Please give example.
Thank You.

推荐答案

通过引用传回值...
Pass value back by reference...
void func1(int &value){value = some_value;}


使用方法:


to use:

int x;
func1(&x);


如果您对Alber Holguin的回答不满意,请看以下示例.
下面的示例向您展示如何从void类型函数中检索值. int * p,这里从main()函数传递一个变量,该变量将在fun()函数中更改.
它通过引用调用传递值.

if you are not satisfied with the answer of Alber Holguin, just see this example.
The following example show you how to retrieve value from void type function. int *p, here pass a variable from main() function and that variable will be changed inside fun() function.
It calls pass value by reference.

#include<stdio.h>
#include<conio.h>
void fun(int *p);/* function prototype */
int main()
{
 clrscr();
 int x=0;
 fun(&x); /* function call*/
 printf("%d",x);
 getch();
return 0;
}
void fun(int *p) /*function body/definition*/
{
 *p=13;/*any int value*/
}


除了其他答案外,从技术上讲这是正确的:如果您确实需要返回某些内容,则使用void函数根本没有意义.毕竟,返回参数是什么?!

我会以某种方式理解您是否已经有一个return参数,然后需要添加其他东西来返回.答案将是:1)通过引用使用参数返回第二个值; 2)使用按值传递的指针,并在函数的代码中更改指向的对象(在C上完成); 3)使用return参数,但是具有不同的类型,例如classstruct,因此所有返回数据都将传递到class/struct的成员中.
但是,不,您要问的是要从void函数返回某些内容.这确实是一个矛盾.实际上,没有可能需要它的情况.



示例:
In addition to the other answers, which are technically correct: if your really need to return something, using a void function makes no sense at all. After all, what is the return parameter for?!

I would somehow understand if you already have one return parameter and then need to add something else to return. The answer would be 1) return second value using a parameter by reference; 2) using pointer passed by value and changing the pointed object in the code of your function (as it is done on C); 3) using return parameter, but with a different type such as class or struct, so all your return data would be passed in the members of the class/struct.

But no, you''re asking about returning something from a void function. This is really an oxymoron. In practice, there is no situation when it can be needed.



Example:
//makes no sense:
void func1(int &value){ value = some_value; }

//how it should be:
int func1(){ return some_value; }



与其他任何参数类型相同.对于引用或指针类型,应谨慎使用:即使销毁类的实例,该对象也应存在,但这与通过引用传递我们的参数完全相同.另请阅读任何C ++手册中有关 l值 的概念.

[END EDIT]

—SA



Same thing with any other parameter type. With reference or pointer type a caution should be used: the object should exist even when an instance of the class is destroyed, but this is exactly same thing as with passing the our parameter by reference. Read also on the concept of l-value in any C++ manual.

[END EDIT]

—SA


这篇关于从虚函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆