【发布时间】: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);
}
【问题讨论】:
-
如果不通过引用传递
num2和num3,main()将如何变化? -
另外,您有两个不同且不相关的问题,为此您应该发布两个不同的问题。
-
这只是comma operator。它将评估
cout << endl,丢弃结果,然后评估另一个cout表达式。
标签: c++ pass-by-reference