1.代码
#include<iostream> template<class T> class Test { private: T m_x; public: friend void print(const Test<T> &test); Test(T x) :m_x(x) { } }; template<class T> void print(const Test<T> &test) { std::cout << test.m_x<< std::endl; }; int main() { Test<int> test(1); print(test); std::cin.get(); return 0; }
上面的程序编译没有问题,链接时候会报例如以下的错误,错误 2 error LNK1120: 1 个无法解析的外部命令,错误 1 error LNK2019: 无法解析的外部符号 "void __cdecl print(class Test<int> const &)" (?print@@YAXABV?
$Test@H@@@Z)。该符号在函数 _main 中被引用 。
解决的方法有两种
1.将友元函数放入函数内部
#include<iostream> template<class T> class Test { private: T m_x; public: friend void print(const Test<T> &test) { std::cout << test.m_x << std::endl; } Test(T x) :m_x(x) { } }; int main() { Test<int> test(1); print(test); std::cin.get(); return 0; }
2.仍旧放在外部,採取声明等方式
#include<iostream> template<class T> class Test; template<class T> void print(const Test<T> &test); template<class T> class Test { private: T m_x; public: friend void print<T>(const Test<T> &test);//这里<T>不可缺少 Test(T x) :m_x(x) { } }; template<class T> void print(const Test<T> &test) { std::cout << test.m_x<< std::endl; }; int main() { Test<int> test(1); print(test); std::cin.get(); return 0; }