How to allow your data structure to take in objects of any class

How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object.

Even better, you can specify what class of objects that ArrayList would store by doing...

new ArrayList()< whateverObject >

I've implemented a linked list data structure in C++ and I'd like to know how I can allow it to do this...

At the moment, I'm just using...

typedef whateverObject ItemType

at the start of my header file for my linked list and then manipulating "ItemType" throughout the implementation of the linked list. So every time I want to change the type, eg instead of using the list for storing strings, I want to store an int, I'll have to change the typedef in my linked list's header but I want to be able to simply use it for any object so...

How?!

Thanks.


Templates are the answer to your question.

Define your linked list as follows :

template<typename ItemType>
class ArrayList
{
  // What's inside your class definition does not need to be changed
  // Include your method definitions here and you'll be fine
};

The type to use is then ArrayList<WhateverObject> .


Use templates. It's a lot to explain so I'll just give you a link where it's explained much better than I'll ever be able to do here: C++ FAQ - Templates.

While you're at it, if you have the time, I suggest you read the whole FAQ, it's really a great resource!


If I have understood well what you ask, templates is what you want.

Take a look here:

http://www.cplusplus.com/doc/tutorial/templates/

链接地址: http://www.djcxy.com/p/87898.html

上一篇: C ++:用于有效插入和检索自定义数据的数据结构

下一篇: 如何让你的数据结构能够接收任何类的对象