歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++中組合類的初始化:冒號語法(常數據成員和引用成員的初始化)

C++中組合類的初始化:冒號語法(常數據成員和引用成員的初始化)

日期:2017/3/1 10:30:39   编辑:Linux編程
  1. #include <iostream>
  2. #include<string>
  3. using namespace std;
  4. class Student
  5. {
  6. int semesHours;
  7. float gpa;
  8. public:
  9. Student(int i)
  10. {
  11. cout << "constructing student.\n";
  12. semesHours = i;
  13. gpa = 3.5;
  14. }
  15. ~Student()
  16. {
  17. cout << "~Student\n";
  18. }
  19. };
  20. class Teacher
  21. {
  22. string name;
  23. public:
  24. Teacher(string p)
  25. {
  26. name = p;
  27. cout << "constructing teacher.\n";
  28. }
  29. ~Teacher()
  30. {
  31. cout << "~Teacher\n";
  32. }
  33. };
  34. class TutorPair
  35. {
  36. public:
  37. TutorPair(int i, int j, string p) :
  38. teacher(p), student(j)
  39. {
  40. cout << "constructing tutorpair.\n";
  41. noMeetings = i;
  42. }
  43. ~TutorPair()
  44. {
  45. cout << "~TutorPair\n";
  46. }
  47. protected:
  48. Student student;
  49. Teacher teacher;
  50. int noMeetings;
  51. };
  52. int main(int argc, char **argv)
  53. {
  54. TutorPair tp(5, 20, "Jane");
  55. cout << "back in main.\n";
  56. return 0;
  57. }
注意:程序裡面的賦值方式,以及構造函數析構函數的調用次序。
[html]
  1. constructing student.
  2. constructing teacher.
  3. constructing tutorpair.
  4. back in main.
  5. ~TutorPair
  6. ~Teacher
  7. ~Student

另外:構造函數初始化常數據成員和引用成員。

[cpp]
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Student
  5. {
  6. public:
  7. Student(int s, int &k) :
  8. i(s), j(k)
  9. {
  10. } //不可以直接賦值
  11. void p()
  12. {
  13. cout << i << endl;
  14. cout << j << endl;
  15. }
  16. protected:
  17. const int i;
  18. int &j;
  19. };
  20. int main(int argc, char **argv)
  21. {
  22. int c = 123;
  23. Student s(9818, c);
  24. s.p();
  25. return 0;
  26. }
[cpp]
  1. 9818
  2. 123
Copyright © Linux教程網 All Rights Reserved