1. (论述题) 定义一个Person 类,包括姓名Name 和年龄Age 。定义Student 类继承Person ,增加成员学号Num 。再定义CollegeStudents 类继承Student ,增加成员专业Speciality 。每个类均包括构造函数、析构函数、设置信息函数和显示信息函数。在main 函数中分别定义三个类的对象进行测试
/*
先调用派生类析构,再调用基类析构,析构调用按照声明的逆序进行
*
/结果:
测试 Person 类:
Person 构造函数被调用
姓名: Alice, 年龄: 30
测试 Student 类:
Person 构造函数被调用
Student 构造函数被调用
姓名: Bob, 年龄: 20
学号: S123456
测试 CollegeStudent 类:
Person 构造函数被调用
Student 构造函数被调用
CollegeStudent 构造函数被调用
姓名: Charlie, 年龄: 22
学号: C654321
专业: Computer Science
CollegeStudent 析构函数被调用
Student 析构函数被调用
Person 析构函数被调用
Student 析构函数被调用
Person 析构函数被调用
Person 析构函数被调用
#include <iostream>
#include <string>
using namespace std;
// 基类 Person
class Person {
protected:
string Name;
int Age;
public:
// 构造函数
Person(const string& name = "", int age = 0) : Name(name), Age(age) {
cout << "Person 构造函数被调用" << endl;
}
// 析构函数
virtual ~Person() {
cout << "Person 析构函数被调用" << endl;
}
// 设置信息函数
void setInfo(const string& name, int age) {
Name = name;
Age = age;
}
// 显示信息函数
virtual void displayInfo() const {
cout << "姓名: " << Name << ", 年龄: " << Age << endl;
}
};
// 派生类 Student
class Student : public Person {
protected:
string Num; // 学号
public:
// 构造函数
Student(const string& name = "", int age = 0, const string& num = "")
: Person(name, age), Num(num) {
cout << "Student 构造函数被调用" << endl;
}
// 析构函数
~Student() override {
cout << "Student 析构函数被调用" << endl;
}
// 设置信息函数
void setInfo(const string& name, int age, const string& num) {
Person::setInfo(name, age);
Num = num;
}
// 显示信息函数
void displayInfo() const override {
Person::displayInfo();
cout << "学号: " << Num << endl;
}
};
// 派生类 CollegeStudent
class CollegeStudent : public Student {
private:
string Speciality; // 专业
public:
// 构造函数
CollegeStudent(const string& name = "", int age = 0, const string& num = "", const string& speciality = "")
: Student(name, age, num), Speciality(speciality) {
cout << "CollegeStudent 构造函数被调用" << endl;
}
// 析构函数
~CollegeStudent() override {
cout << "CollegeStudent 析构函数被调用" << endl;
}
// 设置信息函数
void setInfo(const string& name, int age, const string& num, const string& speciality) {
Student::setInfo(name, age, num);
Speciality = speciality;
}
// 显示信息函数
void displayInfo() const override {
Student::displayInfo();
cout << "专业: " << Speciality << endl;
}
};
// 测试主函数
int main() {
// 测试 Person 类
cout << "测试 Person 类:" << endl;
Person p("Alice", 30);
p.displayInfo();
cout << endl;
// 测试 Student 类
cout << "测试 Student 类:" << endl;
Student s("Bob", 20, "S123456");
s.displayInfo();
cout << endl;
// 测试 CollegeStudent 类
cout << "测试 CollegeStudent 类:" << endl;
CollegeStudent cs("Charlie", 22, "C654321", "Computer Science");
cs.displayInfo();
cout << endl;
return 0;
}