3.1 自封装字段
【1】源代码
1 class Student 2 { 3 typedef enum { MALE, FEMALE } SEX; 4 5 public: 6 QString m_name; 7 int m_nAge; 8 SEX m_sex; 9 QString m_strID; 10 QString m_department; 11 };
【2】自封装字段
1 // 自封装 2 class Student 3 { 4 typedef enum { MALE, FEMALE } SEX; 5 6 public: 7 QString getName() 8 { 9 return m_name; 10 } 11 void setName(QString name) 12 { 13 m_name = name; 14 } 15 int getAge() 16 { 17 return m_nAge; 18 } 19 void setName(int nAge) 20 { 21 m_nAge = nAge; 22 } 23 SEX getSex() 24 { 25 return m_sex; 26 } 27 void setSex(SEX sex) 28 { 29 m_sex = sex; 30 } 31 QString getID() 32 { 33 return m_ID; 34 } 35 void setID(QString id) 36 { 37 m_ID = id; 38 } 39 QString getDepartment() 40 { 41 return m_department; 42 } 43 void setDepartment(QString department) 44 { 45 m_department = department; 46 } 47 48 private: 49 QString m_name; 50 int m_nAge; 51 SEX m_sex; 52 QString m_ID; 53 QString m_department; 54 };
【3】总结
直接访问一个字段,但与字段之间的耦合关系逐渐变得笨拙。
为这个字段建立取值/设值函数,并且只以这些函数来访问字段。
Good Good Study, Day Day Up.
顺序 选择 循环 总结