本文介绍了抽象类的链表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这应该是简单的,但我花了很多时间试图找出为什么我不能制作一个链接列表的不同的类继承自同一个抽象类

I feel like this should be something simple but I have spent tons of time trying to figure out why I cannot make a linked list of different classes that inherit from the same abstract class

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

each of the classes (i.e. BadCruisingShootingAgent) I am pushing to the front of the linked list are inheriting from the abstract class Agent.

我得到.. ..
错误:不能声明'Node :: data'为抽象类型'Agent'

I am getting....error: cannot declare field 'Node::data' to be of abstract type 'Agent'

我的main.cpp文件读取:

my main.cpp file reads:

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);
}



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

I don't understand why this does not work while if I just manually write there are no problems.

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

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

Then my linked list's class function push_front is defined as:

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;
}


推荐答案

对不是引用或指针的类型。因此,当您创建 LinkedList< Agent> 时,底层节点分配代理因为它是一个抽象类型。

You can't perform polymorphism on types that aren't references or pointers. Thus, when you create a LinkedList<Agent>, the underlying nodes are allocating an Agent, which can't be created because it is an abstract type.

因此,使用 LinkedList< Agent *> 您的链接列表中的导出类型。

Thus, using LinkedList<Agent*> lets you polymorphically store different derived types in your linked list.

这篇关于抽象类的链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:20