为什么Pass By Ref不起作用

时间:2015-07-30 20:50:59

标签: c++ pass-by-reference

通过引用传递似乎不起作用。输出的第二行应该使用引用,而是输出与之前相同的内容。

double passByValue(double, double);
double passByRef(double&, double&);

int main(){    
    double firstNumber=0, secondNumber=0;
    char quit =' ';
    while (quit != 'y'){

        cout <<"Please enter your first number: ";
        cin >> firstNumber;

        cout << "\nPlease enter your second number: ";
        cin >> secondNumber;

        cout <<firstNumber <<"\t" << secondNumber << "\t" << passByValue(firstNumber, secondNumber)<<endl;
        cout <<firstNumber <<"\t" << secondNumber << "\t" << passByRef(firstNumber ,secondNumber )<<endl;

        cout <<"Do you want to quit? y/n";
        cin >> quit;
    }
}

double passByValue(double first, double second){
    first +=5;
    second +=5;
    double sum =first + second;
    return sum;
}

double passByRef(double &a, double &b){
    a +=5;
    b +=5;
    double sum = a + b;
    return sum;
}

2 个答案:

答案 0 :(得分:1)

试试这个:

double sum = passByValue(firstNumber, secondNumber);
cout << firstNumber <<"\t" << secondNumber << "\t" << sum <<endl;
sum = passByRef(firstNumber, secondNumber);
cout << firstNumber <<"\t" << secondNumber << "\t" << sum <<endl;

这可确保您看到因调用该函数而对firstNumbersecondNumber所做的更改。

答案 1 :(得分:1)

代码是正确的,你的解释不是。
在致电firstNumber后尝试显示secondNumberpassByReference,您应该知道:

0     0     10  
0     0     10  
5     5  

问题在于,当您拨打passByValue时,这些行

first +=5;
second +=5;

实际上没有增加firstNumbersecondNumberfirstsecond是副本。
另一方面,当你通过引用传递时,它们不是5,