多态置换原则初始化基类对象

 1 #include "TStudent.h"
 2 
 3 enum EStudentStatus  //大学生系别不同,用枚举分类
 4 {
 5     eFullTime, ePartTime, eExchange
 6 };
 7 
 8 //每学期,每名大学生允许注册的课程数目
 9 const short MAX_COURSES_FOR_STUDENT = 5;//短整型常量
10 enum EDepartment
11 {
12     eAccounting, eBusiness, eEngineering, eMathematics, ePhysics, eChemistry, eArts, eUnknown
13 };
14 
15 TStudent::TStudent(const char theName[],unsigned long theSSN,const char theBirthDate[],const char theAddress[],
16     EStudentStatus theStatus,EDepartment theDepartment)
17     :TPerson(theName,theSSN,theBirthDate,theAddress)
18     _status(theStatus),_department(theDepartment),_numCourses(0)
19 {
20     //现在只需为学生部分执行初始化,课程列表为空
21     for (int i = 0; i < MAX_COURSES_FOR_STUDENT; i++)
22         _enrolled[i] = 0;
23 }
24 
25 TStudent::TStudent(const TStudent& copy)
26     :TPerson(copy),
27     _status(copy._status),
28     _department(copy._department),
29     _numCourses(copy._numCourses)
30 {
31     //正确的复制课程
32     for (int i = 0; i < MAX_COURSES_FOR_STUDENT; i++)
33         if (copy._enrolled[i] != 0)
34             this->_enrolled[i] = new TCourse(*copy._enrolled[i]);
35 }
36 
37 //赋值操作符
38 TStudent& TStudent::operator=(const TStudent& other)
39 {
40     if (this == &other) return *this;//自我复制
41     TPerson::operator=(other);//调用基类赋值运算符
42     this->_status = other._status;
43     this->_department = other._department;
44     this->_numCourses = other._numCourses;
45 
46     //正确地复制课程
47     for(int i=0;i<MAX_COURSES_FOR_STUDENT;i++)
48         if (this->_enrolled[i] != 0 && other._enrolled[i] == 0)
49         {
50             delete _enrolled[i];//删除TCourse类对象
51         }
52         else if (this->_enrolled[i] == 0 && other._enrolled[i] != 0)
53         {
54             this->_enrolled[i] = new TCourse(*(other._enrolled[i]));
55         }
56         else if (this->enrolled[i] != 0 && other._enrolled[i] != 0)
57         {
58             *(this->_enrolled[i]) = *(other._enrolled[i]);
59         }
60     return *this;
61 }
62 TStudent::~TStudent()
63 {
64     for (int i = 0; i < MAX_COURSES_FOR_STUDENT; i++)
65     {
66         if (this->_enrolled[i] != 0)
67         {
68             delete _enrolled[i];
69         }
70     }
71 }
72 
73 
74 void TStudent::Print() const
75 {
76     cout << "Name:" << TPerson::GetName() << endl;
77     cout << "Address:" << TPerson::GetAddress() << endl;
78     cout << "This person is a" << statusLabels[(int)_status] << "Student in the department of" << departmemtNames[(int)_department];
79 }
原文地址:https://www.cnblogs.com/zhengzhe/p/6561911.html