1

好的,例如,我必须使用 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;
}
4

2 回答 2

1

您应该使用模板:

#include <list>

typedef std::list<Patient> Patients;
typedef std::list<Record> Records;
typedef std::list<Service> Services;
于 2013-01-11T19:35:53.503 回答
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

于 2013-01-11T19:33:19.853 回答