简单抽象数据类型链表
我的类
class Product
{
...
};
class Perishable : public : Product
{
public:
int getday();
};
我想包含易腐烂对象和产品对象的集合,并希望通过链接列表来完成。
通常对于链表,我们有类似的东西
class linkedlist
{
struct List
{
int item;
ListNode* next;
}
//.... all the functions
};
,但我在这里遇到一个问题,因为我想存储在 item 中的数据不是 int 而是 Product 或 Perishable,我如何将其实现为链表?
my classes
class Product
{
...
};
class Perishable : public : Product
{
public:
int getday();
};
I want to contain a collection of both perishable and product object together and hope to do it by means of a linked list.
Usually for linked list we have something like
class linkedlist
{
struct List
{
int item;
ListNode* next;
}
//.... all the functions
};
but i have a problem here since the data i want to store in item is not an int but either a Product or a Perishable, how do i implement it as a linked list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
Product*
存储为链接列表中的一项。您应该将虚拟
方法添加到基类Product
中,这些方法将在运行时根据此指针指向的对象的实际类型分派到适当的方法。You can store the
Product*
as an item in the linked list. You should addvirtual
methods to the base classProduct
which will be dispatched to the appropriate method during run time depending on the actual type of object pointed by this pointer.您需要模板。 C++ 中的模板支持泛型编程。在类 LinkedList 之前声明模板后,您可以将 int 项替换为 T 项,其中 T 是占位符,并将根据您实例化对象的方式替换为适当的数据类型(自定义或原始)。
You need Templates. Templates in C++ support generic programming. After declaring template before your class LinkedList you can replace your int item with a T item where T is the place holder and will be substituted for an appropriate data type (custom or primitive) depending upon how you instantiate your object.