通过引用函数和语法调用

时间:2015-07-07 12:48:33

标签: c++ pass-by-reference

代码按升序排序3个数字。但是,swap函数已被引用调用。为什么还必须通过引用调用sort函数?我的问题是交换函数已被引用调用。那么,为什么还要通过引用来排序函数呢?我糊涂了。其次,cout << endl,没有给出任何错误,所以我错误地压了逗号。怎么样?

#include <iostream>


using namespace std;


void swap ( int& a, int& b );
void sort ( int a, int b, int c );


int main() {

    int num1, num2, num3;

    cout << "Enter first number => ";
    cin  >> num1;
    cout << "Enter second number => ";
    cin  >> num2;
    cout << "Enter third number => ";
    cin  >> num3;

    cout << endl,
    cout << "Before sorting numbers\n" << num1
         << " " << num2 << " " << num3 << endl;

    sort( num1, num2, num3 );

    cout << "After sorting numbers\n" << num1
    << " " << num2 << " " << num3 << endl;

    return 0;
}


void swap ( int& a, int& b ) {

    int temp = a;
    a = b;
    b = temp;
}
void sort ( int a, int b, int c ) {
//void sort ( int& a, int& b, int& c )

    if (a > b)
        swap(a, b);

    if (a > c)
        swap(a, c);

    if (b > c)
        swap(b, c);
}

1 个答案:

答案 0 :(得分:-1)

当您调用sort函数时,会在该函数的范围内创建三个新变量。这些变量是您在main函数中传递的三个变量的副本。这三个变量将被传递到swap函数,该函数需要两个整数地址。您传递的变量地址仅限于sort函数内的范围。你可以使用指针来保持一切更有条理。

int main() {

    int *num1, *num2, *num3;

    cout << "Enter first number => ";
    cin  >> *num1;
    cout << "Enter second number => ";
    cin  >> *num2;
    cout << "Enter third number => ";
    cin  >> *num3;

    cout << endl,
    cout << "Before sorting numbers\n" << *num1
         << " " << *num2 << " " << *num3 << endl;

    sort( num1, num2, num3 );

    cout << "After sorting numbers\n" << *num1
    << " " << *num2 << " " << *num3 << endl;

    return 0;
}


void swap ( int *a, int *b ) {

    int *temp = a;
    a = b;
    b = temp;
}
void sort ( int *a, int *b, int *c ) {

    if (*a > *b)
        swap(a, b);

    if (*a > *c)
        swap(a, c);

    if (*b > *c)
        swap(b, c);
}

我实际上没有机会编译它,但我今天晚些时候会看看它是否有效。