【问题标题】:Call by reference function and syntax通过引用函数和语法调用
【发布时间】:2015-09-24 23:08:34
【问题描述】:

代码按升序对 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);
}

【问题讨论】:

  • 如果不通过引用传递num2num3main() 将如何变化?
  • 您知道std 命名空间中存在sortswap 函数吗?通过在代码中包含using namespace std,您自己的函数可能会与标准函数发生冲突,尤其是在这种特定情况下的swap 函数。
  • 另外,您有两个不同且不相关的问题,为此您应该发布两个不同的问题。
  • 这只是comma operator。它将评估cout &lt;&lt; endl,丢弃结果,然后评估另一个cout 表达式。

标签: c++ pass-by-reference


【解决方案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);
}

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

【讨论】:

  • 这行不通,因为您将int 传递给期望int* 的函数。为什么要使用指针而不是只使用两个函数的引用?
  • 这段代码有严重的问题。在main 内部,变量num1num2num3未初始化的指针。如果你很幸运,当你尝试取消引用它们时程序会崩溃。 swap 函数无效,因为您交换的是按值传递的参数,而不是它们指向的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-01
  • 2013-04-29
  • 2015-05-18
  • 1970-01-01
相关资源
最近更新 更多