从一个函数传递值到另一个函数。

3

我是C++编程世界的新手,我还没有完全理解如何将一个函数的输出作为另一个函数的输入使用(如果可能的话该如何实现)。

#include <iostream>
using namespace std;

int func(int l, int m) {
    int x = l * m;
    return x;
}

int code(x?) {
    ...
}

我想使用func的输出(值x)作为code的输入,这是否可能?我该怎么做?

谢谢帮助。

编辑1:

非常感谢回答。也可以使用指针在函数之间传递值吗?


1
我的三分钱 - Benny K
1
虽然与此无关,但由于您是新手,以下提示可能会有所帮助:不要使用 using namespace std;,因为它被认为是一种糟糕的做法,可能会使用不必要的内容污染您的工作环境。建议只需输入 std:: 或者至少对您正在使用的对象进行输入,例如 using std::cout; - User.cpp
5个回答

4

函数只有在执行时才会拥有值。

您可以从第二个函数调用第一个函数,

或者从第一个函数调用,将返回值读入变量并将该值作为第二个函数的参数,

或者直接将第一个函数的调用返回值作为第二个函数的某个参数。

以下是三种选项的示例,使用1、2、3作为任意整数。

变体1:

int func(int l, int m) {
    int x = l * m;
    return x;
}

int code(void) {
    int ValueFromOtherFuntion=func(1,2);
    return 3;
}

变量2:

int func(int l, int m)
{
    int x = l * m;
    return x;
}

int code(int XfromOtherFunction)
{
    return 3;
}

int parentfunction(void)
{
    int ValueFromOtherFuntion=func(1,2);
    return code(ValueFromOtherFunction);
}   

变体3:

int func(int l, int m)
{
    int x = l * m;
    return x;
}

int code(int XfromOtherFunction)
{
    return 3;
}

int parentfunction(void)
{
    return code(func(1,2));
}   

3

是的,您要寻找的是函数组合。

int sum(int a, int b)
{
    return a + b;
}

int square(int x)
{
    return x*x;
}

int main()
{
    std::cout << square(sum(5, 4)); //will calculate (5+4)squared
}

3

当您编写函数时,请假设您已经拥有所有输入,并继续编写您希望该函数执行的内容。

至于何时使用该函数,请使用“嵌套函数”或将函数放在另一个函数中,例如:

code(func(l, m));

函数func将首先执行并返回值x,因此留下了code(x),之后将执行。就像剥洋葱一样:一层接着一层。


1
#include <iostream>

int func(int l, int m) {
    int x = l * m;
    return x;
}

void code(int x) { // argument type is the same as the return type of func
  std::cout << x;
}

int main (){
   int result = func(1 ,2); // either store it
   code(func(1, 2));        // or pass it directly.
   std::cout << result;
   return -1;
}

0
你可以在主函数中调用它(或者在任何其他作用域内): code(func(l,m))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接