类模板与友元函数链接问题
来源:互联网 发布:goodsync mac 编辑:程序博客网 时间:2024/05/16 05:29
测试环境:windows 7 vs2013
上面的程序编译没有问题,链接时候会报如下的错误,错误 2 error LNK1120: 1 个无法解析的外部命令,错误 1 error LNK2019: 无法解析的外部符号 "void __cdecl print(class Test<int> const &)" (?print@@YAXABV?$Test@H@@@Z),该符号在函数 _main 中被引用 。
2.仍旧放在外部,采取声明等方式
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;}
0 0
- 类模板与友元函数链接问题
- [solved] g++ 模板类中的友元函数 链接出错
- 模板类与友元函数
- 友元函数模板问题
- 在类模板中使用友元函数的问题
- 模板类的友元模板函数
- 模板类的 友元模板函数
- 类模板遇到友元函数模板
- 链接器工具错误 LNK2019 - 模板类里声明友元函数
- 模板友元函数
- C++类模板及友元类模板,友元函数模板
- 模板与友元
- 模板类和友元函数
- 模板类的友元函数
- 模板类的友元函数
- 模板类和友元函数
- 类模板中使用友元函数
- 模板类中使用友元函数
- 简单的Android页面跳转
- 如何查看errno 错误代码
- STM32W108无线射频模块串行通信接口
- CSRF
- Squid正向代理的身份验证
- 类模板与友元函数链接问题
- Binder学习一——基础数据结构
- 关于C指针
- CSRF 攻击的应对之道
- Android基础-简单的动画实现 *补间动画 *透明度渐变 *旋转动画 *位移动画 *如果需要几个效果整合到一起,需要将所有效果全部放到set里
- 学习Javascript闭包(Closure)
- 类和对象
- Windows下mysql忘记root密码的解决方法
- ubuntu下安装nvidia显卡驱动