How to allow your data structure to accept objects of any class - C ++

How should I do it? As you know in Java, you can use an ArrayList and it will accept any object as long as you drop it to what it is when you retrieve the object.

Even better, you can specify which class of objects ArrayList will store by doing ...

new ArrayList () <whateverObject>

I implemented a linked list structure in C ++, and I would like to know how I can allow this ...

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

typedef anyObject ItemType

at the beginning of my header file for my linked list, and then manipulate “ItemType” throughout the implementation of the linked list. Therefore, every time I want to change the type, for example. instead of using a list to store strings, I want to save an int, I will have to change the typedef in the header of the linked list, but I want to be able to just use it for any object, so ...

How?!

Thank.

+3
source share
4 answers

Templates are the answer to your question.

Define your linked list as follows:

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

Type used then ArrayList<WhateverObject>.

+6
source

. , , , - : ++ FAQ - .

, , FAQ, !

+5

java , Object. ++ . , Object , ++ . - , "void *". - , ? , . , , , .

+2

Source: https://habr.com/ru/post/1731176/


All Articles