// 函数返回值为引用 #include < iostream.h > int a[] = { 1 , 3 , 5 , 7 , 9 }; int & index( int ); // 声明返回引用的函数 void main(){ cout << index( 2 ) << endl; index( 2 ) = 25 ; // a[2] = 25; cout << index( 2 ) << endl;} // 引用就是变量的别名,这里是返回一个别名,一个变量的别名 int & index( int i){ return a[i]; }
// 引用举例 #include < iostream > using namespace std; int & max( int & num1, int & num2); int & min( int & num1, int & num2); void main(){ int n1,n2; cout << " Enter two numbers: " ; cin >> n1 >> n2; max(n1,n2) = 0; cout << " \nAftrer putting zero in largest,then numbers are: " << n1 << " and " << n2 << endl; cout << " Enter two numbers: " ; cin >> n1 >> n2; min(n1,n2) = 0 ; cout << " \nAftrer putting zero in smallest,then numbers are: " << n1 << " and " << n2 << endl;} int & max( int & num1, int & num2){ return (num1 > num2 ? num1:num2);} int & min( int & num1, int & num2){ return (num1 < num2 ? num1:num2);}