在类模板中实现友元函数
今天试了一个重载运算符函数的例子,里面是利用有元函数对对象进行私有成员的访问;为了加上扩展性,我加上了类模板;程序如下:
1 #include <iostream>
2 using namespace std;
3
4
5 template <typename T>
6 class complex
7 {
8 public:
9 complex(T x, T y){m_x=x;m_y=y;}
10 private:
11 T m_x;
12 T m_y;
13
14 friend ostream& operator<<(ostream &s,const complex<T> &t);
15 };
16
17 template <typename T>
18 ostream & operator<<(ostream &s,const complex<T> &t)
19 {
20 s<<t.m_x<<"+"<<t.m_y<<"i";
21 return s;
22 }
23
24 int main()
25 {
26 complex<double> tt1(1.9, 2.8);
27 std::cout << tt1 << endl;
28
29 complex<int> tt2(1, 2);
30 std::cout << tt2 << endl;
31 }
编译过程如下:
正在编译...
Test.cpp
正在链接...
Test.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 complex<int> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$complex@H@@@Z) ,该符号在函数 _main 中被引用
Test.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 complex<double> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$complex@N@@@Z) ,该符号在函数 _main 中被引用
Debug/Test.exe : fatal error LNK1120: 2 个无法解析的外部命令
迅速百度,求解。 发现上面代码存的问题:
friend ostream& operator<<<T>(ostream &s,const complex<T> &t);
http://topic.csdn.net/u/20070910/14/291db915-dd3f-4bf1-9b95-72abc0387ff9.html
模板在使用之前必须先声明。模板的使用由友元声明构成,不是由模板的声明构成。实际的模板声明必须在友元声明之前。
问题完美解决;