C++模板类重载"<<"未定义错误

来源:互联网 发布:专升本网络教育要多久 编辑:程序博客网 时间:2024/06/05 05:25

在使用C++的模板类进行编程的时候,重载"<<"运算符时,如果定义不当,会出现未定义的情况,错误为LNK2019。


这个问题的原因是由于C++的模板编译机制造成的,解决问题的方式是在类中声明<<运算符时,需要在运算符和参数之间的位置,添加类似<T>标识,具体如下:

template<typename T_Vertex, typename T_Edge>
class CMatrixGraph
{
friend ostream & operator<< <T_Vertex, T_Edge> (ostream &os, CMatrixGraph<T_Vertex, T_Edge> &g);

.......

}


template<typename T_Vertex, typename T_Edge>
ostream &operator<<(ostream &os, CMatrixGraph<T_Vertex, T_Edge> &g)
{
int nVertexNum = g.GetVertexNum();


for (int i = 0; i < nVertexNum; ++i)
{
for (int j = 0; j < nVertexNum; ++j)
{
os << g.GetEdgeAt(i, j) << ' ';
}
os << endl;
}
return os;
}


重新编译,错误消失。


0 0