Reputation: 29
I'm trying to overload the << operator
in this class, but the compiler gives me Pila
is not a type error (Pila
would be stack, the name of the class). GetNElem
is another function that I did not include, don't worry.
#include <vector>
#include <iostream>
using namespace std;
template <class T>
class Pila {
private:
vector <T> elem;
public:
/* Pila(){
} */
Pila ( int n ) {
elem.resize(n);
}
void print(ostream & f_out){
for (int i = 0; i < getNElem(); i++)
f_out << elem[i] << " ";
return;
}
};
ostream& operator << (ostream& f_out, Pila p ){
p.print(f_out);
return f_out;
}
Upvotes: 1
Views: 120
Reputation: 172924
Pila
is a class template, you need to specify template argument when use it. And you can make operator<<
a function template, then
template <typename T>
ostream& operator << (ostream& f_out, Pila<T> p ){
p.print(f_out);
return f_out;
}
BTW: It would be better to pass p
by reference to avoid copy operation on Pila
which constains a std::vector
, and make print
a const
member function.
template <class T>
class Pila {
...
void print(ostream & f_out) const {
for (int i = 0; i < getNElem; i++)
f_out << elem[i] << " ";
}
};
template <typename T>
ostream& operator << (ostream& f_out, const Pila<T>& p ){
p.print(f_out);
return f_out;
}
Upvotes: 4