Hola,
He hecho este código, que consiste en una coleccion donde se pueden almacenar cualquier tipo de objetos. En este caso pruebo con enteros.
Este es el código:
coleccion.h
#ifndef _COLECCION_H_
#define _COLECCION_H_
#include <vector>
using namespace std;
template <typename T>
class Coleccion{
public:
vector<T*> v;
Coleccion(){}
Coleccion(const vector<T>& vc);
int numElem() const{ return (int)v.size(); }
T& operator[](int i)const;
Coleccion<T>& operator<<(const T& elem);
Coleccion<T>& operator+=(const Coleccion<T>& c);
};
template <typename T>
ostream& operator<<(ostream& os, const Coleccion<T>& c){
for(int i=0; i<c.numElem(); i++)
os<<c[i]<<" ";
return os;
}
#endif
coleccion.cpp
#include <iostream>
#include <ostream>
#include <vector>
#include "coleccion.h"
using namespace std;
template <typename T>
Coleccion<T>::Coleccion(const vector<T>& vc){
for(int i=0; i< (int)vc.size();i++)
(*this)<<vc[i];
}
template <typename T>
T& Coleccion<T>::operator [](int i) const{
return *v[i];
}
template <typename T>
Coleccion<T>& Coleccion<T>::operator<<(const T& elem){
v.push_back(new T(elem));
return *this;
}
template <typename T>
Coleccion<T>& Coleccion<T>::operator +=(const Coleccion<T> &c){
*this = *this+c;
return *this;
}
main.cpp
#include "coleccion.h"
#include <iostream>
#include <ostream>
#include <vector>
#include <string>
void main(){
Coleccion<int> c;
c<<1<<2;
}
Si en el main elimino la línea "c<<1<<2;" compila sin errores. Pero con esa línea me da este error:
1>main.obj : error LNK2019: unresolved external symbol "public: class Coleccion<int> & __thiscall Coleccion<int>::operator<<(int const &)" (??6?$Coleccion@H@@QAEAAV0@ABH@Z) referenced in function _main
Si en cambio escribo todo el código en coleccion.cpp funciona perfectamente.
No soy capaz de ver la causa. Alguien lo ve?
Gracias