类模板,模板类的友元函数、模板类的左移运算符重载
类模板在声明与实现分开为两个文件时,在使用时需要使用 类模板的.cpp文件(一般重命名为.hpp)
类模板的友元函数需要在声明的时候加上 template<typename T> 的标识
在具体实现的时候同样需要加上template<typename T>标识,并且所有的使用到的类型的地方需要加上<T>
.h声明
template<typename T>
friend A<T> addA(const A<T>& a, const A<T>& b);
.cpp(.hpp)实现
template<typename T>
A<T> addA(const A<T>& a,const A<T>& b)
{
A<T> tmp;
//....
return tmp;
}
其他文件的使用
#include "Test.cpp"
A<int> c(30);
A<int> d(20);
A<int> v = addA<int>(c,d);
注意:对于使用友元重载运算符 <<的时候 在声明的时候是不需要加上template<typename T> 的。
friend ostream & operator<< <T> (ostream& os,const Vector<T>& a);
但是需要特别注意中间的<T> 是必须的
template<typename T> ostream& operator<<(ostream& os,const Vector<T>& a){ for (int i =0 ;i <a.m_len;i++) { os << a[i]<<" "; } os<<endl; return os; }
留言评论
暂无留言