Template (C ++) - not sure if it is correct

I am a student and I am making a static library for arrays in C ++, so I do not need to rewrite the code every time during the lessons.

I'm in my second year in high school, so I'm not an expert. I want my code to be compatible with all types (int, float, ecc.), But I have problems.

Can you see my code?

// slarray.h #if !defined _SLARRAY_ #define _SLARRAY_ template <typename Tipo> class Array { public: void inserisci(); void visualizza(); void copia(Tipo*); Array(short); ~Array(); private: Tipo* ary; short* siz; }; #endif 

 // slarray.cpp #include <iostream> #include "slarray.h" unsigned short i; unsigned short j; template <typename Tipo> void Array<Tipo>::inserisci() { for (i = 0; i < *siz; i++) { std::cout << i << ": "; std::cin >> ary[i]; } } template <typename Tipo> void Array<Tipo>::visualizza() { for (i = 0; i < *siz; i++) { std::cout << ary[i] << " "; } } template <typename Tipo> void Array<Tipo>::copia(Tipo* arycpy) { for (i = 0; i < *siz; i++) { *(arycpy + i) = ary[i]; } } template <typename Tipo> Array<Tipo>::Array(short n) { siz = new short; *siz = n; ary = new Tipo[n]; } template <typename Tipo> Array<Tipo>::~Array() { delete[] ary; delete siz; } 

The code gives me errors when I try to initialize a class with:

 Array <int> vct(5); 
+4
source share
1 answer

Template implementations should be visible to translation units that specialize in them.

Move the implementations to the header file with cpp .

A few other notes:

  • unsigned short i;unsigned short j; must be local, there is no need to have them as global variables.

  • Macros starting with _ followed by an uppercase letter are reserved, so _SLARRAY_ is illegal, rename it.

  • Implement the assignment operator and copy constructor, otherwise all copies will be shallow.

I assume you cannot use std , otherwise you know that containers already exist there, right?

+2
source

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


All Articles