#include <iostream>
using namespace std;
//Template1
template <typename _T1>
class Scaler
{
private:
_T1 mValue;
public:
Scaler<_T1> operator+(Scaler<_T1> rVin);//赋值函数
Scaler(_T1 t);
template <typename _T>//不能和_T1同名, 且必须是模板函数,<<的重载,因为friend函数并不是类中的函数,
//使用friend的函数
friend ostream & operator<<(ostream &os, Scaler<_T> rIn);
};
template <typename _T1>
inline Scaler<_T1>::Scaler(_T1 t)//注意 inline的位置
{
mValue = t;
}
template <typename _T1>
inline Scaler<_T1> Scaler<_T1>::operator+(Scaler<_T1> t)//注意返回类型 还有类名都是 Scaler<_T1> 而不是Scaler
{
return Scaler<_T1>(mValue + t.mValue);
}
template <typename _T1>
ostream &operator<<(ostream &os, Scaler<_T1> rIn)//以模板类为参数的函数,肯定得是模板函数
{
os << rIn.mValue;
}
int main()
{
Scaler<int> a(5);
Scaler<int> b(6);
Scaler<int> c = a + b;
cout << c << endl;
return 0;
}
c++ template
最新推荐文章于 2024-06-04 10:54:26 发布