用c加加写一个基类:过境人员,派生类:游客、卡车司机、商务旅客的长代码,具体要求1.从一个抽象基类和几个非抽象派生类创建一个层次结构。 2.在类描述中包含一个在创建对象后不会改变的唯一数字标识符: 3. 实现所有构造函数、必要的设置和获取方法、析构函数。 4.根据条件重新加载赋值运算符,比较运算符==,输出运算符到流<<。5.创建一个指向基类的指针数组,填充并对该数组进行一定的操作,以及统计每个类的对象个数。
时间: 2023-05-13 17:05:12 浏览: 71
以下是基类和派生类的长代码:
```c++
#include <iostream>
using namespace std;
class TransitPerson {
protected:
int id;
static int count;
public:
TransitPerson(int id) : id(id) { count++; }
virtual ~TransitPerson() { count--; }
int getId() const { return id; }
virtual void print() const = 0;
static int getCount() { return count; }
};
int TransitPerson::count = 0;
class Tourist : public TransitPerson {
private:
string name;
public:
Tourist(int id, string name) : TransitPerson(id), name(name) {}
~Tourist() {}
string getName() const { return name; }
void setName(string name) { this->name = name; }
void print() const { cout << "Tourist " << name << " with ID " << id << endl; }
};
class TruckDriver : public TransitPerson {
private:
string licensePlate;
public:
TruckDriver(int id, string licensePlate) : TransitPerson(id), licensePlate(licensePlate) {}
~TruckDriver() {}
string getLicensePlate() const { return licensePlate; }
void setLicensePlate(string licensePlate) { this->licensePlate = licensePlate; }
void print() const { cout << "Truck driver with license plate " << licensePlate << " and ID " << id << endl; }
};
class BusinessTraveler : public TransitPerson {
private:
string company;
public:
BusinessTraveler(int id, string company) : TransitPerson(id), company(company) {}
~BusinessTraveler() {}
string getCompany() const { return company; }
void setCompany(string company) { this->company = company; }
void print() const { cout << "Business traveler from " << company << " with ID " << id << endl; }
};
int main() {
TransitPerson* people[3];
people[0] = new Tourist(1, "Alice");
people[1] = new TruckDriver(2, "ABC123");
people[2] = new BusinessTraveler(3, "XYZ Inc.");
for (int i = 0; i < 3; i++) {
people[i]->print();
}
cout << "Total number of transit people: " << TransitPerson::getCount() << endl;
for (int i = 0; i < 3; i++) {
delete people[i];
}
return 0;
}
```
这个程序定义了一个抽象基类 TransitPerson 和三个派生类 Tourist、TruckDriver 和 BusinessTraveler。每个人都有一个唯一的数字标识符 id,并且可以打印自己的信息。程序还创建了一个指向基类的指针数组,填充并对该数组进行一定的操作,以及统计每个类的对象个数。
阅读全文