书中页数:P202
代码名称:ref-fcn.cc refret-ex.cc
//ref-fcn.cc
#include <iostream>
using std::cout; using std::endl;
#include <string>
using std::string;
char &get_val(string &str, string::size_type ix)
{
return str[ix]; // get_val assumes the given index is valid
}
int main()
{
string s("a value");
cout << s << endl; // prints a value
get_val(s, 0) = 'A'; // changes s[0] to A
cout << s << endl; // prints A value
return 0;
}
// refret-ex.cc
#include <iostream>
using std::cout; using std::endl;
// get returns a reference to an element in the given array
int &get(int *arry, int index) { return arry[index]; }
int main() {
int ia[10]; // array of ten uninitialized ints
for (int i = 0; i != 10; ++i)
get(ia, i) = i; // call get to assign values to the elements
for (auto i : ia) // print the elements
cout << i << " ";
cout << endl;
return 0;
}