fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5.  
  6. struct Course;
  7. ostream &operator<<(ostream &os, Course c);
  8.  
  9.  
  10. struct Course {
  11. string name;
  12. Course(string n) {
  13. name = n;
  14. }
  15. Course(const Course &c) {
  16. cout << "Copying course" << endl;
  17. name = c.name;
  18. }
  19. Course &operator=(const Course &c) {
  20. cout << "Assigning course" << endl;
  21. name = c.name;
  22. return *this;
  23. }
  24. };
  25.  
  26.  
  27. struct Student {
  28. int id;
  29. Course *courses[5];
  30. int size;
  31. Student(int num) {
  32. id = num;
  33. for (int i = 0; i < 5; i++) {
  34. courses[i] = new Course("Course");
  35. }
  36. size = 0;
  37. }
  38. Student(const Student &s) {
  39. cout << "Copying student" << endl;
  40. id = s.id;
  41. for (int i = 0; i < 5; i++) {
  42. Course *temp = new Course(s.courses[i]->name);
  43. courses[i] = temp;
  44. }
  45. }
  46. Student &operator=(const Student &s) {
  47. cout << "Assigning student" << endl;
  48. id = s.id;
  49. for (int i = 0; i < 5; i++) {
  50. courses[i] = s.courses[i];
  51. }
  52. return *this;
  53. }
  54. ~Student() {
  55. for (int i = 0; i < 5; i++) {
  56. delete courses[i];
  57. }
  58. }
  59. void print() {
  60. cout << id << ": " << endl;
  61. for (int i = 0; i < 5; i++) {
  62. cout << courses[i]->name << endl;
  63. }
  64. }
  65. void addCourse(const Course& c)
  66. {
  67. delete courses[size];
  68. Course* temp = new Course(c);
  69. courses[size] = temp;
  70. size++;
  71. }
  72. };
  73.  
  74. ostream &operator<<(ostream &os, Course *c) {
  75. return os << c->name << endl;
  76. }
  77.  
  78. int main() {
  79. Student one(2342134);
  80. Course cs246("cs246");
  81. Course cs245("cs245");
  82. one.addCourse(cs246);
  83. one.addCourse(cs245);
  84. one.print();
  85. Student two = one;
  86. two.print();
  87. }
  88.  
  89.  
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Copying course
Copying course
2342134: 
cs246
cs245
Course
Course
Course
Copying student
2342134: 
cs246
cs245
Course
Course
Course