2

我觉得这应该很简单,但我花了很多时间试图弄清楚为什么我不能制作从同一个抽象类继承的不同类的链表

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

我得到....错误:无法将字段“Node::data”声明为抽象类型“代理”

我的 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;
}
4

1 回答 1

7

您不能对不是引用或指针的类型执行多态性。因此,当您创建 a 时LinkedList<Agent>,底层节点正在分配 an Agent,因为它是抽象类型,所以无法创建。

因此, usingLinkedList<Agent*>允许您在链表中多态地存储不同的派生类型。

于 2012-11-18T04:01:19.080 回答