C++学习笔记35 方法模版
2014-08-20 10:27
417 查看
C++允许模版化类中的单个方法,这些方法可以在一个类模版中,也可以在一个非模版化的类中。
在编写一个模版化的类方法时,实际上是为不同类型编写不同版本的方法,在类模版中,方法模版对赋值运算符和复制构造函数非常有用。
要注意的是,不能用方法模版编写虚方法和析构函数。
1.一个普通类中的方法模版例子:
2.一个模版类中的方法模版例子
其实两者的差别并不大。
3.如果同时存在同名的函数,方法模版不会替换同名非模版方法。非模版方法是优先于模版方法的,相当于模版方法在该实例会被覆盖,这个会在下两篇中详细介绍。
例子:
运行截图:
在编写一个模版化的类方法时,实际上是为不同类型编写不同版本的方法,在类模版中,方法模版对赋值运算符和复制构造函数非常有用。
要注意的是,不能用方法模版编写虚方法和析构函数。
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> }
运行截图:
相关文章推荐
- [C++学习笔记]虚方法
- 设计模式C++学习笔记之九(Template Method模板方法模式)
- 初探C++函数模版学习笔记
- C++学习笔记之:虚函数之虚表地址打印方法
- C++学习笔记34 模版的原理
- C++学习的一些笔记-->2:防止头文件多次导入造成重复编译的方法
- 【C++】【学习笔记】【019】覆盖方法和重载方法
- C++学习笔记->静态属性和静态方法
- C++学习笔记24,方法重写与方法隐藏
- C++学习笔记4--静态属性 静态方法 虚方法 抽象方法 多态性 析构函数 运算符重载 多继承 虚继承
- 金庸小说考试之模板方法模式学习笔记[C++版]
- C++学习笔记 string 中处理字符的方法
- C++模版学习笔记 非类型形参
- C++学习笔记5:从方法到属性(面向对象基础)
- 学雷锋之工厂方法模式学习笔记[C++版]
- 学雷锋之工厂方法模式学习笔记[C++版]
- 【C++学习笔记】C++控制台程序隐藏界面运行的方法
- C++析构函数的作用及其定义方法的学习笔记
- C++学习笔记36 模版的显式具体化(template specialization)和显式实例化(template instantiation)
- C++学习笔记(6)——多重继承类对象的构造函数参数的传递方法