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(Course *c) {
  66. delete courses[size];
  67. courses[size] = c;
  68. size++;
  69. }
  70. };
  71.  
  72. ostream &operator<<(ostream &os, Course *c) {
  73. return os << c->name << endl;
  74. }
  75.  
  76. int main() {
  77. Student one(2342134);
  78. Course* cs246 = new Course("cs246");
  79. Course* cs245 = new Course("cs245");
  80. one.addCourse(cs246);
  81. one.addCourse(cs245);
  82. one.print();
  83. Student two = one;
  84. two.print();
  85. }
  86.  
  87.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
2342134: 
cs246
cs245
Course
Course
Course
Copying student
2342134: 
cs246
cs245
Course
Course
Course