//模板友元.cpp:定义控制台应用程序的入口点。
//
#include"stdafx.h"
#include<iostream>
usingnamespacestd;
template<classT>
classBox;
template<classT>
Box<T>operator+(constBox<T>&,constBox<T>&);
template<classT>
Box<T>operator+(constBox<T>&,constT&);
template<classT>
Box<T>operator+(constT&,constBox<T>&);
template<classT>
ostream&operator<<(ostream&,constBox<T>&);
template<classT>
classBox...{
public:
Box();//{
//tt=0;
//}
Box(constT&);
voidf();
voidf(T&);
staticvoidsta();
friendBoxoperator+<T>(constBox<T>&,constBox<T>&);//要带<T>或者<>表示这个是一个模板
friendBoxoperator+<>(constBox<T>&,constT&);
friendBoxoperator+<>(constT&,constBox<T>&);
friendostream&operator<<<T>(ostream&,constBox<T>&);
private:
Ttt;
};
template<classT>
voidBox<T>::sta()...{
Ta=(T)100;
cout<<a<<"Thisisastaticfunction!"<<endl;
}
template<classT>
Box<T>::Box<T>()...{//构造函数后面可以带<T>,不过编译会报警的
//Box<T>::类的成员函数的使用要用类作用域解析符号,但是对模板而言要使用模板形式的
tt=0;
}
template<classT>
Box<T>::Box(constT&newt)...{
tt=newt;
}
template<classT>
voidBox<T>::f()...{//但是类的非构造函数如果使用了<T>,
//即:voidBox<T>::f<T>(),就不对了,因为类作用域解析符号已经足够体现T的意义
//静态函数也不例外,可以拿上面的sta函数试试
Tt=100;
tt=t;
cout<<tt<<endl;
}
template<classT>
voidBox<T>::f(T&a)...{
Tt=100;
tt=t;
cout<<tt<<endl;
}
template<classT>
Box<T>operator+<T>(constBox<T>&a,constT&b)...{//友元在类声明里面要带<T>或<>在函数名后表示这个是一个模板
//而在外部定义时可以不带的
returnBox<T>(a.tt+b);
}
template<classT>
Box<T>operator+(constT&a,constBox<T>&b)...{
returnb+a;
}
template<classT>
Box<T>operator+(constBox<T>&a,constBox<T>&b)...{
returnBox<T>(a.tt+b.tt);
}
template<classT>
ostream&operator<<(ostream&os,constBox<T>&a)...{
returnos<<a.tt<<endl;
}
int_tmain(intargc,_TCHAR*argv[])
...{
Box<int>a(10);
Box<int>b(5);
Box<int>c;
c=100+b+10;
cout<<a<<endl
<<b<<endl
<<c<<endl;
//c.f<int>();
c.f();
Box<int>::sta();
return0;
}
本文通过一个具体的C++示例详细介绍了如何在模板类中声明和定义友元函数,以及如何实现运算符的重载。展示了不同类型的运算符重载方法,并解释了在模板上下文中正确声明和使用友元的重要性。
5533

被折叠的 条评论
为什么被折叠?



