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/