0

我从此代码中收到以下错误:错误 1 ​​错误 LNK2019:未解析的外部符号“class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class 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 点

我知道这个错误通常意味着我没有定义函数,但是,它已定义。如果我注释掉 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;
}
4

1 回答 1

0

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

template <class T> friend ostream &operator<<(ostream &os, const Point<T> &X);
于 2013-08-05T18:10:43.607 回答