编写一个控制台程序,在该程序中构造一个Person基类,再分别构造Student和Teacher派生类,要求具有不同的特征和行为,能通过静态成员自动记录由不同派生类创建的对象的人数。
时间: 2024-03-14 16:47:30 浏览: 72
好的,我会根据你的要求来回答你的问题。
首先,我们需要定义一个Person基类,代码如下:
```cpp
#include <iostream>
class Person {
public:
Person(std::string name, int age) : m_name(name), m_age(age) {
++s_count;
}
virtual void show() {
std::cout << "Name: " << m_name << std::endl;
std::cout << "Age: " << m_age << std::endl;
}
virtual ~Person() {
--s_count;
}
static int getCount() {
return s_count;
}
private:
std::string m_name;
int m_age;
static int s_count;
};
int Person::s_count = 0;
```
在Person类中,我们定义了一个静态成员变量s_count,用于记录由不同派生类创建的对象的人数。在构造函数中,我们将s_count加1,代表创建了一个新的对象。在析构函数中,我们将s_count减1,代表销毁了一个对象。同时,我们还定义了一个静态成员函数getCount,用于获取s_count的值。
接下来,我们需要定义两个派生类Student和Teacher:
```cpp
class Student : public Person {
public:
Student(std::string name, int age, int score) : Person(name, age), m_score(score) {
++s_count;
}
void show() override {
std::cout << "Name: " << m_name << std::endl;
std::cout << "Age: " << m_age << std::endl;
std::cout << "Score: " << m_score << std::endl;
}
~Student() override {
--s_count;
}
private:
int m_score;
static int s_count;
};
int Student::s_count = 0;
class Teacher : public Person {
public:
Teacher(std::string name, int age, std::string title) : Person(name, age), m_title(title) {
++s_count;
}
void show() override {
std::cout << "Name: " << m_name << std::endl;
std::cout << "Age: " << m_age << std::endl;
std::cout << "Title: " << m_title << std::endl;
}
~Teacher() override {
--s_count;
}
private:
std::string m_title;
static int s_count;
};
int Teacher::s_count = 0;
```
在Student和Teacher类中,我们同样定义了一个静态成员变量s_count,用于记录由不同派生类创建的对象的人数。在构造函数和析构函数中,同样需要将s_count加1和减1。
最后,我们编写一个控制台程序测试一下:
```cpp
int main() {
Person* p1 = new Student("张三", 18, 90);
Person* p2 = new Teacher("李四", 35, "教授");
p1->show();
p2->show();
std::cout << "Person count: " << Person::getCount() << std::endl;
std::cout << "Student count: " << Student::getCount() << std::endl;
std::cout << "Teacher count: " << Teacher::getCount() << std::endl;
delete p1;
delete p2;
std::cout << "Person count: " << Person::getCount() << std::endl;
std::cout << "Student count: " << Student::getCount() << std::endl;
std::cout << "Teacher count: " << Teacher::getCount() << std::endl;
return 0;
}
```
输出结果为:
```
Name: 张三
Age: 18
Score: 90
Name: 李四
Age: 35
Title: 教授
Person count: 2
Student count: 1
Teacher count: 1
Person count: 0
Student count: 0
Teacher count: 0
```
可以看到,我们成功地创建了一个Person基类和两个派生类Student和Teacher,并且能够通过静态成员自动记录由不同派生类创建的对象的人数。
阅读全文