studentc.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // studentc.cpp -- Student class using containment
  2. #include "studentc.h"
  3. using std::ostream;
  4. using std::endl;
  5. using std::istream;
  6. using std::string;
  7. //public methods
  8. double Student::Average() const
  9. {
  10. if (scores.size() > 0)
  11. return scores.sum()/scores.size();
  12. else
  13. return 0;
  14. }
  15. const string & Student::Name() const
  16. {
  17. return name;
  18. }
  19. double & Student::operator[](int i)
  20. {
  21. return scores[i]; // use valarray<double>::operator[]()
  22. }
  23. double Student::operator[](int i) const
  24. {
  25. return scores[i];
  26. }
  27. // private method
  28. ostream & Student::arr_out(ostream & os) const
  29. {
  30. int i;
  31. int lim = scores.size();
  32. if (lim > 0)
  33. {
  34. for (i = 0; i < lim; i++)
  35. {
  36. os << scores[i] << " ";
  37. if (i % 5 == 4)
  38. os << endl;
  39. }
  40. if (i % 5 != 0)
  41. os << endl;
  42. }
  43. else
  44. os << " empty array ";
  45. return os;
  46. }
  47. // friends
  48. // use string version of operator>>()
  49. istream & operator>>(istream & is, Student & stu)
  50. {
  51. is >> stu.name;
  52. return is;
  53. }
  54. // use string friend getline(ostream &, const string &)
  55. istream & getline(istream & is, Student & stu)
  56. {
  57. getline(is, stu.name);
  58. return is;
  59. }
  60. // use string version of operator<<()
  61. ostream & operator<<(ostream & os, const Student & stu)
  62. {
  63. os << "Scores for " << stu.name << ":\n";
  64. stu.arr_out(os); // use private method for scores
  65. return os;
  66. }