我如何知道函数是否通过值/引用?

时间:2018-03-28 20:52:46

标签: c++

这两个函数在这段代码中加入和减去我需要的两个整数,我怎么知道这个函数是否通过值传递,以及在函数体和void main中打印值的区别是什么。

#include <iostream> 

using namespace std;
void sumAndDifference(int n1, int n2, int sum, int diff) {
    sum = n1 + n2;
    diff = n1 - n2;
}
void main() {
    int sum = 0, diff = 0, x = 200, y = 88;
    sumAndDifference(x, y, sum, diff); //calling the function
    cout << "\n Sum is " << sum << "\n Diff is " << diff;
}
return 0;

#include <iostream> 

using namespace std;
void sumAndDifference(int n1, int n2, int sum, int diff) {
    sum = n1 + n2;
    diff = n1 - n2;
    cout << "\n Sum is " << sum;    //print sum in the function
    cout << "\n Diff is " << diff;   // print diff in the function
}
void main() {
    int sum = 0, diff = 0, x = 200, y = 88;
    sumAndDifference(x, y, sum, diff);   //calling the function
}
return 0;

2 个答案:

答案 0 :(得分:0)

他们正在经历价值。您可以查看签名,例如值foo(int x)和引用foo(int& x)。因此,在您的示例中,要修改 out 参数,您需要使用签名

void sumAndDifference(int n1, int n2, int& sum, int& diff)

答案 1 :(得分:0)

首先我修改了你的代码。

  #include <iostream> 

    using namespace std;
    void sumAndDifference (int n1, int n2, int sum, int diff) 
    { 
        sum = n1 + n2;
        diff = n1 - n2;
    }
    void main () 
    {
        int sum = 0, diff = 0, x = 200, y = 88;
        sumAndDifference (x,y,sum, diff); //calling the function
        cout << "\n Sum is " << sum << "\n Diff is " << diff;   
    }
   //&&
    #include <iostream> 

    using namespace std;
    void sumAndDifference (int n1, int n2,int sum, int diff)
    {
        sum = n1 + n2;
        diff = n1 - n2;
        cout << "\n Sum is " << sum;    //print sum in the function
        cout << "\n Diff is " << diff;   // print diff in the function
    }

    void main ()
    {
        int sum = 0, diff = 0, x = 200, y = 88;
        sumAndDifference (x,y, sum, diff);   //calling the function
    }

其次,这里介绍的两个函数都按值传递参数。 通过引用传递参数的函数示例可以是

void SumAndDifference(int n1, int n2, int &sum, int &diff)