Template (C++) - not sure if correct

2019-06-26 16:20发布

问题:

I'm a student and I'm doing a static library for arrays in C++, so I don't have to rewrite code every time during lessons.

I'm at second year in a secondary school so I'm not an expert. I want my code to be compatible with all type (int, float, ecc.) but I'm having some trouble.

Can you give a look at 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 inizialize the class with:

Array <int> vct(5);

回答1:

Template implementations need to be visible to translation units that specialize them.

Move the implementations to the header file from the cpp.

A few other notes:

  • unsigned short i;unsigned short j; should be made local, there's no need to have them as global variables.

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

  • Implement an assignment operator and copy constructor, otherwise all copying will be shallow.

I'm assuming you can't use std, otherwise you are aware that containers already exist there, right?