- #include <iostream>
- #include<string>
-
- using namespace std;
- class Student
- {
- int semesHours;
- float gpa;
- public:
- Student(int i)
- {
- cout << "constructing student.
";
- semesHours = i;
- gpa = 3.5;
- }
- ~Student()
- {
- cout << "~Student
";
- }
- };
-
- class Teacher
- {
- string name;
- public:
- Teacher(string p)
- {
- name = p;
- cout << "constructing teacher.
";
- }
- ~Teacher()
- {
- cout << "~Teacher
";
- }
- };
-
- class TutorPair
- {
- public:
- TutorPair(int i, int j, string p) :
- teacher(p), student(j)
- {
- cout << "constructing tutorpair.
";
- noMeetings = i;
- }
- ~TutorPair()
- {
- cout << "~TutorPair
";
- }
- protected:
- Student student;
- Teacher teacher;
- int noMeetings;
- };
-
- int main(int argc, char **argv)
- {
- TutorPair tp(5, 20, "Jane");
- cout << "back in main.
";
- 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