好的,例如,我必须使用List ADT创建一个包含多个类的简单医院队列系统。所以我的问题是typedef。我如何进行此操作,因为类型def只能有一种数据类型。
#include <string>
#include "Patients.h"
#include "Records.h"
#include "Services.h"
const int MAX_SIZE = 10000;
typedef Patients ItemType;
typedef Records ItemType; //Error Here
typedef Services ItemType; //Error Here
class List
{
private:
ItemType items[MAX_SIZE];
int size;
public:
List::List();
void List::display();
void List::replace(int index, ItemType item);
bool List::add(ItemType newItem);
bool List::add(int index, ItemType newItem);
void List::remove(int index);
ItemType List::get(int index);
bool List::isEmpty();
int List::getLength();
};
#include <iostream>
#include "List.h" // header file
using namespace std;
// constructor
List::List()
{
size = 0;
}
// add a new item to the back of the list (append)
bool List::add(ItemType newItem)
{
bool success = size < MAX_SIZE;
if (success)
{
items[size] = newItem; // add to the end of the list
size++; // increase the size of the list by one
}
return success;
}
// add a new item at a specified position in the list (insert)
bool List::add(int index, ItemType newItem)
{
bool success = (index >= 1) && (index <= size + 1) && (size < MAX_SIZE);
if (success)
{
for (int pos = size; pos >= index; pos--)
items[pos] = items[pos-1];
items[index-1] = newItem;
size++; // increase the size of the list by one
}
return success;
}
// remove an item at a specified position in the list
void List::remove(int index)
{
bool success = (index >= 1) && (index <= size);
if (success)
{
for (int fromPosition = index + 1; fromPosition <= size; fromPosition++)
items[fromPosition - 2] = items[fromPosition - 1];
size--;
}
}
// get an item at a specified position of the list (retrieve)
ItemType List::get(int index)
{
ItemType dataItem;// = 0;
bool success = (index >= 1) && (index <= size);
if (success)
dataItem = items[index - 1];
return dataItem;
}
// check if the list is empty
bool List::isEmpty()
{
return size == 0;
}
// check the size of the list
int List::getLength()
{
return size;
}
void List::replace(int index, ItemType item)
{
bool success = index >= 1 && index <= getLength();
if (success)
items[index] = item;
}
答案 0 :(得分:1)
您应该使用模板:
#include <list>
typedef std::list<Patient> Patients;
typedef std::list<Record> Records;
typedef std::list<Service> Services;
答案 1 :(得分:0)
我建议您将List
从类更改为类模板。了解std::list<>
如何在标准库中发挥作用以获得更多创意。
所以,你可能有:
template<class ItemType>
class List
{
private:
ItemType items[MAX_SIZE];
int size;
public:
ItemType List::get(int index);
...
};
然后,您可以在声明列表时指定列表数据的类型:
List<Patients> allThePeople;
List<Records> allThePapers;
List<Services> allTheWork;
<小时/> 当然,如果由于课程作业以外的任何原因而创建
List
代码,则应该使用std::list
代替。