简单派生类的构造函数
#include<bits/stdc++.h>
using namespace std;
/**
* 简单派生类的构造函数
* */
class Student {
public:
Student(int n, string nam) {
num = n;
name = nam;
}
protected:
int num;
string name;
};
class Student1: public Student {
public:
Student1(int n, string nam, int a): Student(n, nam) {
age = a;
}
void show() {
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
private:
int age;
};
int main() {
Student1 stud1(10010, "zhangsan", 19);
stud1.show();
return 0;
}
包含子对象派生类的构造函数
#include<bits/stdc++.h>
using namespace std;
/**
* 包含子对象派生类的构造函数
* */
class Student {
public:
Student(int n, string nam) {
num = n;
name = nam;
cout<<"construct: Student "<<"名字为:"<<name<<endl;
}
void display() {
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
}
protected:
int num;
string name;
};
class Student1: public Student {
public:
Student1(int n, string nam, int a, string ma, int n1,string nam1): Student(n, nam), monitor(n1, nam1) {
age = a;
major = ma;
cout<<"construct: Student1"<<endl;
}
void show() {
cout<<"the student is :"<<endl;
display();
cout<<"age:"<<age<<endl;
cout<<"major:"<<major<<endl;
}
void show_monitor() {
cout<<"monitor is:"<<endl;
monitor.display();
}
private:
int age;
string major;
Student monitor;
};
int main() {
Student1 stud1(10010, "zhangsan", 19, "math", 10001, "monitor");
stud1.show();
stud1.show_monitor();
return 0;
}
析构函数
#include<bits/stdc++.h>
using namespace std;
/**
* 析构函数
* */
class A {
public:
A() {
cout<<"constrcu A" <<endl;
}
~A() {
cout<<"destruct A"<<endl;
}
};
class B: public A {
public:
B() {
cout<<"construct B"<<endl;
}
~B() {
cout<<"destruct B"<<endl;
}
};
int main() {
B b;
return 0;
}
输出
constrcu A
construct B
destruct B
destruct A