学习笔记-----C++模板类中友元函数重载输出运算符时提示无法解析的外部符号解决方案
2016-10-18 21:25
357 查看
今天在写单向链表实现线性表的时候打算重载输出运算符用来将线性表输出,结果无奈又遇到了问题。
大致代码如下
<pre name="code" class="cpp">
运行的时候编译器报错说 无法解析的外部符号
想来想去也只能使友元函数出了问题,于是果断百度了解了一下
友元函数虽然可以访问类内部的成员,但是它相对于类是独立的,它的实现不能依赖类。代码中用到模板类template<class T> 而在类内声明友元函数的时候也用到了<T>,所以此时友元函数是依赖于类的实现而实现的,编译器才会报错。
解决方法有两个
第一种:可以将友元函数的实现放在类的内部
第二种:在类的内部声明友元函数的时候在之前为它单独配一个模板类型,然后在外部实现
template<class T>
class chainList : public linearList<T>
{
template<typename U>
friend ostream& operator<<(ostream & out, const chainList<U> & rhs);
public:
......
private:
......
};
//友元函数实现的实现
template<typename U>
ostream & operator<<(ostream & out, const chainList<U> & rhs)
{
......
}
大致代码如下
<pre name="code" class="cpp">
template<class T> class chainList : public linearList<T> { friend ostream& operator<<(ostream & out, const chainList<T> & rhs); public: ...... private: ...... }; //友元函数实现的实现 template<class T> ostream & operator<<(ostream & out, const chainList<T> & rhs) { ...... }
运行的时候编译器报错说 无法解析的外部符号
想来想去也只能使友元函数出了问题,于是果断百度了解了一下
友元函数虽然可以访问类内部的成员,但是它相对于类是独立的,它的实现不能依赖类。代码中用到模板类template<class T> 而在类内声明友元函数的时候也用到了<T>,所以此时友元函数是依赖于类的实现而实现的,编译器才会报错。
解决方法有两个
第一种:可以将友元函数的实现放在类的内部
第二种:在类的内部声明友元函数的时候在之前为它单独配一个模板类型,然后在外部实现
template<class T>
class chainList : public linearList<T>
{
template<typename U>
friend ostream& operator<<(ostream & out, const chainList<U> & rhs);
public:
......
private:
......
};
//友元函数实现的实现
template<typename U>
ostream & operator<<(ostream & out, const chainList<U> & rhs)
{
......
}
相关文章推荐
- C++模板类中声明友元函数重载输入和输出运算符时,提示无法解析的外部符号解决方案
- [VS2013]C++中调用Python脚本提示 error LNK2001: 无法解析的外部符号__imp_PyString_FromString等错误的解决方案
- c++中调用python脚本提示 error LNK2001: 无法解析的外部符号 __imp_Py_Initialize等错误的解决方法
- c++中调用python脚本提示 error LNK2001: 无法解析的外部符号 __imp_Py_Initialize等错误的解决方法
- c++连接mysql并提示“无法解析的外部符号 _mysql_server_init@12”解决方法
- visual studio中提示无法解析的外部符号的解决方案
- c++连接mysql并提示“无法解析的外部符号 _mysql_server_init@12”解决方法
- C++中模板类使用友元模板函数 和友员非模版函数!使用不当出现编译错误:无法解析的外部符号…
- 调用宇视SDK接口后提示“无法解析的外部符号....”解决方案
- c++中调用python脚本提示 error LNK2001: 无法解析的外部符号 __imp_Py_Initialize等错误的解决方法
- 【VS-C++】WinSocket开发时提示无法解析的外部符号
- c++中调用python脚本提示 error LNK2001: 无法解析的外部符号
- 无法解析的外部符号问题的相应解决方案
- 错误提示:error LNK2019: 无法解析的外部符号和fatal error LNK1120: 1 个无法解析的外部命令
- dcmtk提示无法解析的外部符号(unresolved external symbol)的解决方法
- 无法解析的外部符号 ---一般解决方案
- 关于C++ 无法解析的外部符号
- “LNK2001: 无法解析的外部符号错误”的一种解决方案
- 【C++】关于error LNK 2019 无法解析的外部符号
- 关于编译eMule0.48a 提示: zlib.lib(gzio.obj) : error LNK2019: 无法解析的外部符号 __imp__strerror ,该符号在函数 _gzerror 中被引用