C++允许模版化类中的单个方法,这些方法可以在一个类模版中,也可以在一个非模版化的类中。
在编写一个模版化的类方法时,实际上是为不同类型编写不同版本的方法,在类模版中,方法模版对赋值运算符和复制构造函数非常有用。
要注意的是,不能用方法模版编写虚方法和析构函数。
1.一个普通类中的方法模版例子:
#include <iostream>
using namespace std;
class man{
private:
string name;
public:
man(const string &m):name(m){
}
template <class T>
void show(T t){
cout<<"This is "<<t<<" vesion:"<<name<<endl;
}
};
int main()
{
man m("guang");
m.show(100);
m.show("string");
m.show(0.999);
}
运行结果:
2.一个模版类中的方法模版例子
其实两者的差别并不大。
#include <iostream>
#include <string>
using namespace std;
template<class T>
class man{
private:
string name;
T data;
public:
man(const string &m,T d):name(m),data(d){
}
template <class TT>
void show(TT t){
cout<<"This is "<<t<<" vesion:"<<endl;
cout<<"name="<<name<<" ,data="<<data<<endl;
}
};
int main()
{
man<int> m("guang",10);
m.show(100);
m.show("string");
m.show(0.999);
cout<<endl<<endl;
man<string> ms("jing","love");
ms.show(100);
ms.show("string");
ms.show(0.999);
}
运行截图:
3.如果同时存在同名的函数,方法模版不会替换同名非模版方法。非模版方法是优先于模版方法的,相当于模版方法在该实例会被覆盖,这个会在下两篇中详细介绍。
例子:
#include <iostream>
#include <string>
using namespace std;
template<class T>
class man{
private:
string name;
T data;
public:
man(const string &m,T d):name(m),data(d){
}
<span style="color:#ff0000;">void show(int i)const{
cout<<"这里是非模版方法!!"<<endl;
cout<<"name="<<name<<" ,data="<<data<<endl<<endl;
}
template <class TT>
void show(TT t)const{
cout<<"这里是模版方法:"<<endl;
cout<<"This is "<<t<<" vesion:"<<endl;
cout<<"name="<<name<<" ,data="<<data<<endl;
}</span>
};
int main()
{
man<int> m("guang",10);
m.show(100);
m.show("string");
m.show(0.999);
cout<<endl<<endl;
man<string> ms("jing","love");
ms.show(100);
ms.show("string");
ms.show(0.999);
<span style="white-space:pre"> </span>
}
运行截图: