【发布时间】:2019-06-27 07:27:57
【问题描述】:
我在学习模板时遇到过以下练习:
#include <iostream>
using namespace std;
template <class T>
class A {
T _v;
public:
A() {}
A(T v) : _v(v) {}
friend ostream & operator<<(ostream & c, const A<T> & v);
};
template <class T>
ostream & operator<<(ostream & c, const A<T> & v){
c << v._v; return c;
}
int main()
{
A<int>a(10);
cout << a << endl;
return 0;
}
这段代码 sn-p 在编译过程中应该会产生错误,它确实会产生错误。这是一个链接器错误,但我无法理解。
我尝试更改几行代码,错误似乎是由模板operator<< 的安装引起的,因为删除该模板并编写特定的运算符会使代码正常工作。我也觉得模板被多次实例化,不仅仅是int。
但是,据我所知,模板定义似乎还不错。我错过了什么?
确切的错误(VS 2017)是: 错误 LNK2019:无法解析的外部符号“class std::basic_ostream > & __cdecl operator &,class A const &)” (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@ std@@@std@@AEAV01@AEBV?$A@H@@@Z) 在 main 函数中引用
【问题讨论】:
-
错误是什么?
-
模板参数没有“继承”到友元函数声明。我会尝试找到一个重复的。