重载& lt; & lt;为什么我得到以下错误

Overloading << with templates: Why am I getting the following error?

本文关键字:lt 错误 为什么 重载      更新时间:2023-10-16
 template <typename T> class Queue
{
template<typename T> ostream& operator<< (ostream& print, const Queue <T>& x)
   {
        print<<"nThe elements are as : n";
        if(q.f!=-1)
        {
            int fr=q.f,rr=q.r;
            while(fr<=rr)
                print<<q.q[fr++]<<" <- ";
        }
        print<<endl;
    }
  //other stuffs
};
  In main():
  Queue<int> q(n); //object creation
  cout<<q; //calling the overloaded << function

显示如下错误:

C:UsersuserDesktopPROGRAMSqueue_using_classes.cpp|16|error: declaration of 'class T'|
C:UsersuserDesktopPROGRAMSqueue_using_classes.cpp|3|error:  shadows template parm 'class T'|
C:UsersuserDesktopPROGRAMSqueue_using_classes.cpp|16|error: 'std::ostream& Queue<T>::operator<<(std::ostream&, const Queue<T>&)' must take exactly one argument

为了使用:

Queue<int> q(n);
cout << q;

函数

ostream& operator<<(ostream& print, const Queue <T>& x)

需要定义为非成员函数。关于这个特殊过载的更多信息,请参阅我对另一个问题的回答。

对于类模板来说,声明一个friend函数是很棘手的。下面是一个展示这个概念的基本程序。

// Forward declaration of the class template
template <typename T> class Queue;
// Declaration of the function template.
template<typename T> std::ostream& operator<< (std::ostream& print, const Queue <T>& x);
// The class template definition.
template <typename T> class Queue
{
   // The friend declaration.
   // This declaration makes sure that operator<<<int> is a friend of Queue<int>
   // but not a friend of Queue<double>
   friend std::ostream& operator<<<T> (std::ostream& print, const Queue& x);
};
// Implement the function.
template<typename T> 
std::ostream& operator<< (std::ostream& print, const Queue <T>& x)
{
   print << "Came here.n";
   return print;
}
int main()
{
   Queue<int> a;
   std::cout << a << std::endl;
}