mardi 27 septembre 2016

Output Stream with templates c++ doesn't work [duplicate]

This question already has an answer here:

I have a template class and i want to overload the output operator <<, but my code doesn't work, I don't know why... I don't know how do the same thing, but with the input operator... Can you help me?

This is my code:

#include <iostream>

template<class TypeData, int S>
class TD{
  private:
      int size;
      int augmentation;
      int capacity;

      TypeData * array;

      void changeCapacity();

  public:
    TD();

    TD(const TD<TypeData,S> & array);

    TypeData & operator [](int position) const;

    void addElement(TypeData element);

    friend std::ostream & operator << (std::ostream & output, const TD<TypeData, S> & array);

    ~TD();
};

Here the implementation:

template<class TypeData, int S>
TD<TypeData, S>::TD(): 
size(0), augmentation(S), capacity(S){
    this->array = new TypeData[S];
}

template<class TypeData, int S>
TD<TypeData, S>::TD(const TD<TypeData,S> & array): size (array.size),
augmentation(array.augmentation), capacity(array.capacity){
    this->array = new TypeData[array.capacity];

    for (int i = 0; i < array.size; i++){
        this->array[i] = array[i];
    }
}

template<class TypeData, int S>
TypeData& TD<TypeData, S>::operator [](int position) const{
    if (position > this->size){
            return this->array[0];
    }

    return this->array[position];
}

template<class TypeData, int S>
void TD<TypeData, S>::addElement(TypeData element){
    if (this->capacity <= this->size){
        TypeData * ptTmp = new TypeData[this->capacity];

        for (int i = 0; i < this->size; i++){
            ptTmp[i] = this->array[i];
        }

        delete this->array;

        this->capacity += this->augmentation;
        this->array = new TypeData[this->capacity];

        for (int i = 0; i < this->size; i++){
            this->array[i] = ptTmp[i];
        }

        delete[] ptTmp;
    }

    this->array[size] = element;
    size++;
}

template<class TypeData, int S>
std::ostream & operator << (std::ostream & output, const TD<TypeData, S> & array){
    for (int i = 0; i < array.size; i++){
        output << array[i] << " - ";
    }

    return output;
}

Here the main:

int main(){

   TD<int,20> t;
   t.addElement(5);
   t.addElement(10);

   std::cout << t << std::endl;

   return 0;
}

I have this error:

Undefined symbols for architecture x86_64:
  "TD<int, 20>::~TD()", referenced from:
    _main in test9-134633.o
  "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, TD<int, 20> const&)", referenced from:
      _main in test9-134633.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Aucun commentaire:

Enregistrer un commentaire