抽象类的链接列表?

时间:2012-11-18 03:39:52

标签: c++ linked-list abstract-class

我觉得这应该是简单的事情,但我花了很多时间试图找出为什么我不能创建从同一抽象类继承的不同类的链表

我推送到链表前面的每个类(即BadCruisingShootingAgent)继承自抽象类Agent。

我得到...... 错误:无法将字段'Node :: data'声明为抽象类型'Agent'

我的main.cpp文件是:

int main()
{
LinkedList<Agent> *agentList= new LinkedList<Agent>();

agentList->push_front(*(new BadCruisingShootingAgent));
agentList->push_front(*(new BadFollowingDisarmedAgent));
agentList->push_front(*(new BadFollowingShootingAgent));
agentList->push_front(*(new BadStationaryDisarmedAgent));
agentList->push_front(*(new BadStationaryShootingAgent));
agentList->push_front(*(new GoodCruisingDisarmedAgent));
agentList->push_front(*(new GoodCruisingShootingAgent));
agentList->push_front(*(new GoodFollowingDisarmedAgent));
agentList->push_front(*(new GoodFollowingShootingAgent));
agentList->push_front(*(new GoodStationaryDisarmedAgent));
agentList->push_front(*(new GoodStationaryShootingAgent));

for(int i=0; i<agentList->size(); i++)
{
  cout    << agentList->at(i).getType()<<" "<<agentList->at(i).nextMovingDirection(10,10)<<" "<<agentList->at(i).shootingDirection(10,10)<<endl;
}



return(0);
}

我不明白为什么这不起作用,如果我只是手动写,没有问题。

 Agent *a= new BadCruisingShootingAgent;
 cout    << a->getType()<<" "<<a->extMovingDirection(10,10)<<" "<<a->shootingDirection(10,10)<<endl;

然后我的链表的类函数push_front定义为:

template <typename T>
void LinkedList<T>::push_front(const T& val)
{
    //make a new node
Node<T>* newOne = new Node<T>(val);

//push it onto the front of the list
newOne->next = this->head;
this->head = newOne;

//increase the length of the list by one
this->length++;
}

我的节点类定义为:

template <typename T>
class Node
{
public:

    Node(const T& d);

    T data;
    Node<T>* next;
};

template <typename T>
Node<T>::Node(const T& d)
: data(d)
{
    this->next = NULL;
}

1 个答案:

答案 0 :(得分:7)

您不能对不是引用或指针的类型执行多态。因此,当您创建LinkedList<Agent>时,基础节点正在分配Agent,因为它是抽象类型而无法创建。{/ p>

因此,使用LinkedList<Agent*>可以在链接列表中以多态方式存储不同的派生类型。