无法解析的外部符号
定义了一个模版类,然后在类里面重载流插入>>符号和流输出<<符号,结果在VC6.0里能通过编译,在VC2003.net和VC2005.net里却不能通过编译,请问是怎么回事?源代码如下:
# include<iostream>
using namespace std;
template<class type>
class test
{
public:
friend istream & operator >>(istream & ,test<type> &);
friend ostream & operator <<(ostream & ,test<type> &);
private:
type a;
type b;
};
template<class type>
istream & operator >>(istream & cin,test<type> & t1)
{
cin>>t1.a>>t1.b;
return cin;
}
template<class type>
ostream & operator <<(ostream & cout,test<type> & t1)
{
cout<<t1.a<<endl;
cout<<t1.b<<endl;
return cout;
}
int main()
{
test<int> t1;
cin>>t1;
cout<<t1<<endl;
return 0;
}
在VC2003.net和VC2005.net里的编译信息如下:
------ 已启动生成: 项目: try2, 配置: Debug Win32 ------
正在编译...
try2.cpp
正在链接...
try2.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 test<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$test@H@@@Z) ,该符号在函数 _main 中被引用
try2.obj : error LNK2019: 无法解析的外部符号 "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class test<int> &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$test@H@@@Z) ,该符号在函数 _main 中被引用
Debug/try2.exe : fatal error LNK1120: 2 个无法解析的外部命令
生成日志保存在“file://c:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\try2\try2\Debug\BuildLog.htm”中
try2 - 3 错误,0 警告
---------------------- 完成 ---------------------
生成: 0 已成功, 1 已失败, 0 已跳过
另外,把
friend istream & operator >>(istream & ,test<type> &);
friend ostream & operator <<(ostream & ,test<type> &);
这两句改成
friend istream & operator >>< >(istream & ,test<type> &);
friend ostream & operator <<< >(ostream & ,test<type> &);
或
friend istream & operator >><type>(istream & ,test<type> &);
friend ostream & operator <<<type>(ostream & ,test<type> &);
就能通过编译,但却在VC6.0里不能通过编译了,请问这是怎么回事,有没有一个比较完美的解决方案,使程序在三种编译器里都能通过编译?
参考答案:加 #ifdef 区分编译器。