/*********************************/
/* 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;
}
模板类的非模板友元函数
最新推荐文章于 2024-09-06 16:17:58 发布