- #include <iostream>
- #include<string>
-
- using namespace std;
- class Student
- {
- int semesHours;
- float gpa;
- public:
- Student(int i)
- {
- cout << "constructing student.\n";
- semesHours = i;
- gpa = 3.5;
- }
- ~Student()
- {
- cout << "~Student\n";
- }
- };
-
- class Teacher
- {
- string name;
- public:
- Teacher(string p)
- {
- name = p;
- cout << "constructing teacher.\n";
- }
- ~Teacher()
- {
- cout << "~Teacher\n";
- }
- };
-
- class TutorPair
- {
- public:
- TutorPair(int i, int j, string p) :
- teacher(p), student(j)
- {
- cout << "constructing tutorpair.\n";
- noMeetings = i;
- }
- ~TutorPair()
- {
- cout << "~TutorPair\n";
- }
- protected:
- Student student;
- Teacher teacher;
- int noMeetings;
- };
-
- int main(int argc, char **argv)
- {
- TutorPair tp(5, 20, "Jane");
- cout << "back in main.\n";
- return 0;
- }
注意:程序裡面的賦值方式,以及構造函數析構函數的調用次序。
[html]
- constructing student.
- constructing teacher.
- constructing tutorpair.
- back in main.
- ~TutorPair
- ~Teacher
- ~Student
另外:構造函數初始化常數據成員和引用成員。
[cpp]
- #include <iostream>
- #include <string>
-
- using namespace std;
-
- class Student
- {
- public:
- Student(int s, int &k) :
- i(s), j(k)
- {
- } //不可以直接賦值
- void p()
- {
- cout << i << endl;
- cout << j << endl;
- }
- protected:
- const int i;
- int &j;
- };
-
- int main(int argc, char **argv)
- {
- int c = 123;
- Student s(9818, c);
- s.p();
-
- return 0;
- }
[cpp]
- 9818
- 123