在类模板中重载了运算符,并把该函数声明为友元函数.如果在类体外定义该友元函数(外部函数),则出现如下编译错误:
main.obj : error LNK2019: 无法解析的外部符号"class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class SeqList<int> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$SeqList@H@@@Z), 该符号在函数 _main 中被引用
和
fatal error LNK1120: 1 个无法解析的外部命令
这是一个链接期错误,原因是重载外部运算符函数没有在声明为友元时显式声明其模板参数列表
实际上,如果定义类似
template<typename T>void show(Pig<T>& _pg)
{
_pg.x = 8;//修改Pig类的私有成员
cout << "Pig的成员: " << _pg.x << endl; //参阅Pig类的私有成员!
}
的模板函数,要将其定义为友元函数,应该使用的不是
friend void show(Pig<T>& _pg);
而是
friend void show<T>(Pig<T>& _pg);
或
template<typenameT>
friend void show(Pig<T>& _pg);
,因为show()不是函数的id,show<T>()才是函数的id,所以一定要在定义友元函数时显式声明模板参数表