当一个类的成员是一个对象时,他先构造内部的对象,析构时是相反的顺序。
#include<iostream> #include<string> using namespace std; class Student { private: int age; int height; public: Student(int age1,int height1){ age = age1; height = height1; cout<<"我是学生的构造函数"<<endl; } void printAge(){ cout<<age<<endl; } ~Student(){ cout<<"我是学生的析构函数"<<endl; } }; class Teacher { string name; Student S; public: Teacher(string name1,int s_age, int s_height):S(s_age,s_height)//注意这里给成员对象赋值只能用初始化列表的方法,不然会报错 { name = name1; cout<<"我是Teacher的构造函数"<<endl; } ~Teacher(){ cout<<"我是Teacher的析构函数"<<endl; } }; int main(){ system("chcp 65001"); // Student stu1(13,135); Teacher tea("lhc", 13,135); return 0; }