strc_ref.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //strc_ref.cpp -- using structure references
  2. #include <iostream>
  3. #include <string>
  4. struct free_throws
  5. {
  6. std::string name;
  7. int made;
  8. int attempts;
  9. float percent;
  10. };
  11. void display(const free_throws & ft);
  12. void set_pc(free_throws & ft);
  13. free_throws & accumulate(free_throws &target, const free_throws &source);
  14. int main()
  15. {
  16. free_throws one = {"Ifelsa Branch", 13, 14};
  17. free_throws two = {"Andor Knott", 10, 16};
  18. free_throws three = {"Minnie Max", 7, 9};
  19. free_throws four = {"Whily Looper", 5, 9};
  20. free_throws five = {"Long Long", 6, 14};
  21. free_throws team = {"Throwgoods", 0, 0};
  22. free_throws dup;
  23. set_pc(one);
  24. display(one);
  25. accumulate(team, one);
  26. display(team);
  27. // use return value as argument
  28. display(accumulate(team, two));
  29. accumulate(accumulate(team, three), four);
  30. display(team);
  31. // use return value in assignment
  32. dup = accumulate(team,five);
  33. std::cout << "Displaying team:\n";
  34. display(team);
  35. std::cout << "Displaying dup after assignment:\n";
  36. display(dup);
  37. set_pc(four);
  38. // ill-advised assignment
  39. accumulate(dup,five) = four;
  40. std::cout << "Displaying dup after ill-advised assignment:\n";
  41. display(dup);
  42. // std::cin.get();
  43. return 0;
  44. }
  45. void display(const free_throws & ft)
  46. {
  47. using std::cout;
  48. cout << "Name: " << ft.name << '\n';
  49. cout << " Made: " << ft.made << '\t';
  50. cout << "Attempts: " << ft.attempts << '\t';
  51. cout << "Percent: " << ft.percent << '\n';
  52. }
  53. void set_pc(free_throws & ft)
  54. {
  55. if (ft.attempts != 0)
  56. ft.percent = 100.0f *float(ft.made)/float(ft.attempts);
  57. else
  58. ft.percent = 0;
  59. }
  60. free_throws & accumulate(free_throws & target, const free_throws & source)
  61. {
  62. target.attempts += source.attempts;
  63. target.made += source.made;
  64. set_pc(target);
  65. return target;
  66. }