C++允许模版化类中的单个方法,这些方法可以在一个类模版中,也可以在一个非模版化的类中。 在编写一个模版化的类方法时,实际上是为不同类型编写不同版本的方法,在类模版中,方法模版对赋值运算符和复制构造函数非常有用。 要注意的是,不能用方法模版编写虚方法和析构函数。 1.一个普通类中的方法模版例子:
#include
using namespace std;
class man{
private:
string name;
public:
man(const string &m):name(m){
}
template
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
#include
using namespace std;
template
class man{
private:
string name;
T data;
public:
man(const string &m,T d):name(m),data(d){
}
template
void show(TT t){
cout<<”This is “<<t<<” vesion:”<<endl;
cout<<”name=”<<name<<” ,data=”<<data<<endl;
}
};
int main()
{
man
m.show(100);
m.show(“string”);
m.show(0.999);
cout<<endl<<endl;
man
ms.show(100);
ms.show(“string”);
ms.show(0.999);
}
运行截图: 3.如果同时存在同名的函数,方法模版不会替换同名非模版方法。非模版方法是优先于模版方法的,相当于模版方法在该实例会被覆盖,这个会在下两篇中详细介绍。 例子:
#include
#include
using namespace std;
template
class man{
private:
string name;
T data;
public:
man(const string &m,T d):name(m),data(d){
}
void show(int i)const{
cout<<”这里是非模版方法!!”<<endl;
cout<<”name=”<<name<<” ,data=”<<data<<endl<<endl;
}
template
void show(TT t)const{
cout<<”这里是模版方法:”<<endl;
cout<<”This is “<<t<<” vesion:”<<endl;
cout<<”name=”<<name<<” ,data=”<<data<<endl;
}
};
int main()
{
man
m.show(100);
m.show(“string”);
m.show(0.999);
cout<<endl<<endl;
man
ms.show(100);
ms.show(“string”);
ms.show(0.999);
}
运行截图: —————————————————————————————————————————————————— //写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。 转载请注明出处:https://www.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/c学习笔记35方法模版/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!