我正在尝试编写一个重载的模板类运算符==。我知道如何在课堂上得到它:
template <typename T>
class Point
{
private:
T x;
public:
Point(T X) : x(X) {}
bool operator== (Point &cP)
{
return (cP.x == x);
}
};
但现在我想在模板类之外实现这一点。我读过这篇文章:尝试重载 并在我的代码中添加模板声明:
template <typename> class Point;
template <typename T> bool operator== (Point<T>, Point<T>);
template <class T>
class Point
{
private:
T x;
public:
Point(T X) : x(X) {}
friend bool operator== (Point cP1, Point cP2);
};
template <class T>
bool operator== (Point<T> cP1, Point<T> cP2)
{
return (cP1.x == cP2.x)
}
但是我仍然收到错误:unresolved external symbol "bool __cdecl operator==(class Point<int>,class Point<int>)" (??8@YA_NV?$Point@H@@0@Z) referenced in function _main
当我拿走时friend from :
friend bool operator== (Point cP1, Point cP2);
并希望它是成员函数,则会出现另一个错误:
too many parameters for this function
why?
@Kühl的答案是声明模板化类的模板化友元函数的最宽松的方法。然而,这种方法有一个不明显的副作用:所有模板实例化Point
是所有模板实例的朋友operator==()
。另一种方法是仅使用相同类型的实例化Point
一个朋友。这是通过添加一个来完成的<T>
在朋友宣言中operator==()
.
template <typename T> class Point;
template <typename S>
bool operator== (Point<S>, Point<S>);
template <typename T>
class Point {
// ...
friend bool operator==<T> (Point, Point);
};
参考
http://web.mst.edu/~nmjxv3/articles/templates.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)