简单派生类的构造函数

    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. /**
    4. * 简单派生类的构造函数
    5. * */
    6. class Student {
    7. public:
    8. Student(int n, string nam) {
    9. num = n;
    10. name = nam;
    11. }
    12. protected:
    13. int num;
    14. string name;
    15. };
    16. class Student1: public Student {
    17. public:
    18. Student1(int n, string nam, int a): Student(n, nam) {
    19. age = a;
    20. }
    21. void show() {
    22. cout<<"num:"<<num<<endl;
    23. cout<<"name:"<<name<<endl;
    24. cout<<"age:"<<age<<endl;
    25. }
    26. private:
    27. int age;
    28. };
    29. int main() {
    30. Student1 stud1(10010, "zhangsan", 19);
    31. stud1.show();
    32. return 0;
    33. }

    包含子对象派生类的构造函数

    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. /**
    4. * 包含子对象派生类的构造函数
    5. * */
    6. class Student {
    7. public:
    8. Student(int n, string nam) {
    9. num = n;
    10. name = nam;
    11. cout<<"construct: Student "<<"名字为:"<<name<<endl;
    12. }
    13. void display() {
    14. cout<<"num:"<<num<<endl;
    15. cout<<"name:"<<name<<endl;
    16. }
    17. protected:
    18. int num;
    19. string name;
    20. };
    21. class Student1: public Student {
    22. public:
    23. Student1(int n, string nam, int a, string ma, int n1,string nam1): Student(n, nam), monitor(n1, nam1) {
    24. age = a;
    25. major = ma;
    26. cout<<"construct: Student1"<<endl;
    27. }
    28. void show() {
    29. cout<<"the student is :"<<endl;
    30. display();
    31. cout<<"age:"<<age<<endl;
    32. cout<<"major:"<<major<<endl;
    33. }
    34. void show_monitor() {
    35. cout<<"monitor is:"<<endl;
    36. monitor.display();
    37. }
    38. private:
    39. int age;
    40. string major;
    41. Student monitor;
    42. };
    43. int main() {
    44. Student1 stud1(10010, "zhangsan", 19, "math", 10001, "monitor");
    45. stud1.show();
    46. stud1.show_monitor();
    47. return 0;
    48. }

    析构函数

    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. /**
    4. * 析构函数
    5. * */
    6. class A {
    7. public:
    8. A() {
    9. cout<<"constrcu A" <<endl;
    10. }
    11. ~A() {
    12. cout<<"destruct A"<<endl;
    13. }
    14. };
    15. class B: public A {
    16. public:
    17. B() {
    18. cout<<"construct B"<<endl;
    19. }
    20. ~B() {
    21. cout<<"destruct B"<<endl;
    22. }
    23. };
    24. int main() {
    25. B b;
    26. return 0;
    27. }

    输出

    1. constrcu A
    2. construct B
    3. destruct B
    4. destruct A