重载& lt; & lt;为什么我得到以下错误
Overloading << with templates: Why am I getting the following error?
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;
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- &lt;&lt;操作员在C 中超载错误
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- '&lt;'''&lt;'''&quot的模板类错误''令牌”
- 在尝试超载&lt;&lt;时链接错误2005和1169操作员
- 错误:没有匹配'运算符<<"在'std::cout
- 过载<<比如cout错误
- 重载& lt; & lt;为什么我得到以下错误
- 重载ostream&时转换错误无效;operator< & lt;
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多
- 编译器错误,包括'<'代币
- 重载& lt; & lt;错误