// ================================================ ==============================================
// Name: main. cpp
// Author: ShiGuang
// Version:
// Copyright: sg131971@qq.com
// Description: Hello World in C ++, Ansi-style
// ================================================ ==============================================
# 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;
}
Note: The Assignment Method in the program and the call sequence of the constructor destructor.
Constructing student.
Constructing teacher.
Constructing tutorpair.
Back in main.
~ TutorPair
~ Teacher
~ Student
In addition, the constructor initializes common data members and reference members.
// ================================================ ==============================================
// Name: main. cpp
// Author: ShiGuang
// Version:
// Copyright: sg131971@qq.com
// Description: Hello World in C ++, Ansi-style
// ================================================ ==============================================
# Include <iostream>
# Include <string>
Using namespace std;
Class Student
{
Public:
Student (int s, int & k ):
I (s), j (k)
{
} // Values cannot be assigned directly.
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;
}
9818
123
From Study Notes of sg131971