【问题标题】:LNK2019 Error on overloaded output operatorLNK2019 输出运算符过载错误
【发布时间】:2013-08-05 18:02:40
【问题描述】:

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

【问题讨论】:

标签: c++ templates


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我没有意识到我必须在类 def 中的友元函数上重新建立模板 def。我从一个更大的程序中删除,其他功能都可以工作,但他们不是朋友。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 2013-11-14
  • 2016-10-18
相关资源
最近更新 更多