home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter06 / inventory_referencer.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2004-04-11  |  1.5 KB  |  51 lines

  1. // Inventory Referencer
  2. // Demonstrates returning a reference
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. //returns a reference to a string
  11. string& refToElement(vector<string>& inventory, int i); 
  12.  
  13. int main()
  14. {
  15.     vector<string> inventory;
  16.     inventory.push_back("sword");
  17.     inventory.push_back("armor");
  18.     inventory.push_back("shield");
  19.  
  20.     //displays string that the returned reference refers to 
  21.     cout << "Sending the returned reference to cout:\n";   
  22.     cout << refToElement(inventory, 0) << "\n\n";
  23.  
  24.     //assigns one reference to another -- inexpensive assignment 
  25.     cout << "Assigning the returned reference to another reference.\n";
  26.     string& rStr = refToElement(inventory, 1); 
  27.     cout << "Sending the new reference to cout:\n";
  28.     cout << rStr << "\n\n";
  29.  
  30.     //copies a string object -- expensive assignment
  31.     cout << "Assigning the returned reference to a string object.\n";
  32.     string str = refToElement(inventory, 2);
  33.     cout << "Sending the new string object to cout:\n";
  34.     cout << str << "\n\n";
  35.     
  36.     //altering the string object through a returned reference
  37.     cout << "Altering an object through a returned reference.\n";
  38.     rStr = "Healing Potion";
  39.     cout << "Sending the altered object to cout:\n";
  40.     cout << inventory[1] << endl;
  41.  
  42.     return 0;
  43. }
  44.  
  45. //returns a reference to a string
  46. string& refToElement(vector<string>& vec, int i)
  47. {
  48.     return vec[i];
  49. }
  50.  
  51.