简体   繁体   中英

Class name does not name a type c++

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM