[Plain Text] 纯文本查看 复制代码
// Using an rvalue reference parameter
#include <iostream>
using std::cout;
using std::endl;
int incr10(int&& num); // Function prototype
int main(void)
{
int num(3);
int value(6);
int result(0);
/*
result = incr10(num); // Increment num
cout << endl << "incr10(num) = " << result
<< endl << "num = " << num;
result = incr10(value); // Increment value
cout << endl << "incr10(value) = " << result
<< endl << "value = " << value;
*/
result = incr10(value+num); // Increment an expression
cout << endl << "incr10(value+num) = " << result
<< endl << "value = " << value;
result = incr10(5); // Increment a literal
cout << endl << "incr10(5) = " << result
<< endl << "5 = " << 5;
cout << endl;
return 0;
}
// Function to increment a variable by 10
int incr10(int&& num) // Function with rvalue reference argument
{
cout << endl << "Value received = " << num;
num += 10;
return num; // Return the incremented value
}
[Plain Text] 纯文本查看 复制代码
// Returning a reference
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
double& lowest(double values[], int length); // Function prototype
int main(void)
{
double array[] = { 3.0, 10.0, 1.5, 15.0, 2.7, 23.0,
4.5, 12.0, 6.8, 13.5, 2.1, 14.0 };
int len(sizeof array/sizeof array[0]); // Initialize to number
// of elements
cout << endl;
for(int i = 0; i < len; i++)
cout << setw(6) << array;
lowest(array, len) = 6.9; // Change lowest to 6.9
lowest(array, len) = 7.9; // Change lowest to 7.9
cout << endl;
for(int i = 0; i < len; i++)
cout << setw(6) << array;
cout << endl;
return 0;
}
// Function returning a reference
double& lowest(double a[], int len)
{
int j(0); // Index of lowest element
for(int i = 1; i < len; i++)
if(a[j] > a) // Test for a lower value...
j = i; // ...if so update j
return a[j]; // Return reference to lowest
// element
}