LNK2019重载输出运算符出错

时间:2013-08-05 18:02:41

标签: c++ templates

我从此代码中收到以下错误: 错误1错误LNK2019:未解析的外部符号" class std :: basic_ostream> &安培; __cdecl运算符<<(类std :: basic_ostream>&,类Point const&)" (?? 6 @ YAAAV?$ basic_ostream @ DU?$ char_traits @ D @ std @@@ std @@ AAV01 @ ABV?$ Point @ N @@@ Z)在函数_main G:\ C ++ Part II \ Final Exam中引用\ Point \ Point \ Source.obj Point

我知道这个错误通常意味着我没有定义一个函数,但是,它已被定义。如果我在main中注释掉cout语句,该程序将编译。我猜测我的模板名称遗漏了什么?

#include <iostream>
using namespace std;

template <class T>
class Point{
private:
T x, y;

public:
Point(): x(0), y(0) {cout << "Default Constructor\n";};
Point(T a, T b): x(a), y(b) {cout << "Parameterized Constructor\n";};
Point(const Point &rhs);
~Point() {cout << "Destructor\n";};
friend ostream &operator<<(ostream &os, const Point<T> &X);

};

int main(){
Point <double> B;
cout << B << endl;

return 0;
}
template <class T>
Point<T>::Point(const Point &rhs)
{
x = rhs.x;
y = rhs.y;
cout << "Copy Constructor\n";
}
template <class T>
ostream &operator<<(ostream &os, const Point<T> &X)
{
os << "(" << X.x << ", " << X.y << ")";

return os;
}

1 个答案:

答案 0 :(得分:0)

您在类中声明为朋友的功能实际上与您实现的功能不同。这是一个模板化的功能,声明需要反映出:

template <class T> friend ostream &operator<<(ostream &os, const Point<T> &X);