模板类的非模板友元函数

来源:互联网 发布:sql server 2008密钥 编辑:程序博客网 时间:2024/05/29 18:22
/*********************************/
/* 1.模板类的非模板友元函数
*
/*********************************/
#include <iostream>
using std::cout;
using std::endl;
template <typename T>
class HasFriend{
private:
T item;
static int ct;
public :
HasFriend(const T&i):item(i){ct++;}
~HasFriend(){ct--;}
friend void counts();
friend void reports(HasFriend<T> &);//不是模板函数,只是使用了一个模板做参数,
// 意味必需要使用友元定义显示具体化
// void report(HasFriend<short> &){...};
// void report(HasFriend<double> &){...};
};
template <typename T>
int HasFriend<T>::ct = 0;
void counts()
{
cout<<"int count:"<<HasFriend<int>::ct<<";"<<endl;
cout<<"double count:"<<HasFriend<double>::ct<<";"<<endl;
}
void reports(HasFriend<int> &hf)
{
cout<<"HasFriend<int>: "<<hf.item<<endl;
}
void reports(HasFriend<double> &hf)
{
cout<<"HasFriend<double>: "<<hf.item<<endl;
}
int main()
{
cout<<"No objects declared:"<<endl;
counts();
HasFriend<int> hfi1(10);
cout<<"After hfi1 declared:"<<endl;
counts();
HasFriend<int> hfi2(20);
cout<<"After hfi2 declared:"<<endl;
counts();
HasFriend<double> hfib(10.8);
cout<<"After hfib declared:"<<endl;
counts();
reports(hfi1);
reports(hfi2);
reports(hfib);
return 0;
}
0 0