luc*_*992 2 c++ abstract-class linked-list
我觉得这应该是简单的事情,但我花了很多时间试图找出为什么我不能创建一个从同一个抽象类继承的不同类的链表
我推送到链表前面的每个类(即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);
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这不起作用,如果我只是手动写,没有问题.
Agent *a= new BadCruisingShootingAgent;
cout << a->getType()<<" "<<a->extMovingDirection(10,10)<<" "<<a->shootingDirection(10,10)<<endl;
Run Code Online (Sandbox Code Playgroud)
然后我的链表的类函数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++;
}
Run Code Online (Sandbox Code Playgroud)
我的节点类定义为:
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;
}
Run Code Online (Sandbox Code Playgroud)
您不能对不是引用或指针的类型执行多态.因此,当您创建a时LinkedList<Agent>,底层节点正在分配a Agent,因为它是抽象类型而无法创建.
因此,使用LinkedList<Agent*>允许您在链接列表中以多态方式存储不同的派生类型.