【发布时间】:2016-01-23 16:03:07
【问题描述】:
我正在尝试编写一个重载 operator== 的模板类。我知道如何在课堂上获得它:
template <typename T>
class Point
{
private:
T x;
public:
Point(T X) : x(X) {}
bool operator== (Point &cP)
{
return (cP.x == x);
}
};
但现在我想在模板类之外实现这一点。我读过这篇文章: error when trying to overload << operator and using friend function 并在我的代码中添加模板声明:
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 bool operator== (Point cP1, Point cP2);
并希望它成为成员函数,会有另一个错误:
too many parameters for this function
为什么?
【问题讨论】:
-
或者在静态函数中做
==的工作,在类定义中内联实现友元操作符,调用静态函数,后面可以实现。
标签: c++ templates overloading operator-keyword friend