c++ - 重载 << 使用模板 : Why am I getting the following error?

标签 c++ templates operator-overloading

 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:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|16|error: declaration of 'class T'|
C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|3|error:  shadows template parm 'class T'|
C:\Users\user\Desktop\PROGRAMS\queue_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)

需要定义为非成员函数。参见 my answer to another question有关此特定过载的更多信息。

声明一个 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;
}

关于c++ - 重载 << 使用模板 : Why am I getting the following error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940437/

相关文章:

c++ - MoveWindow死锁?

c++ - 在顶点着色器中将法线转换为 View 空间

c++ - 通过别名定义前向定义的 C++ 结构

c++ - 重载运算符 +

c++ - 需要使用 Book* head 变量重载运算符但不起作用

c++ - 在实现 operator[] 时,我应该如何包括边界检查?

c++ - 多集 C++ 中自定义结构的自定义比较运算符

c++ - 使用运行时常量实例化的函数模板

c++ - 本地类中的成员模板

c++ - 根据数字参数更改模板成员?