c++学习笔记之类模板
生活随笔
收集整理的這篇文章主要介紹了
c++学习笔记之类模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
類是對象的抽象,類模板是類的抽象。
比較兩個數(不同類型)的大小
在類模板內定義成員函數
#include<iostream> using namespace std; template<class numtype> class compare {public:compare(numtype a,numtype b){x=a;y=b;}numtype max(){return(x>y)?x:y;}numtype min(){return(x<y)?x:y;}private:numtype x,y;} ;int main(){compare<int> cmp1(3,7);cout<<cmp1.max()<<"is the maximum of two integer numbers"<<endl;cout<<cmp1.min()<<"is the minimum of two integer numbers"<<endl<<endl;compare<float>cmp2(45.78,93.6);cout<<cmp2.max()<<"is the maximum of two float numbers"<<endl;cout<<cmp2.min()<<"is the minimum of two float numbers"<<endl<<endl;compare<char>cmp3('a','A');cout<<cmp3.max()<<"is the maximum of two characters"<<endl;cout<<cmp3.min()<<"is the minimum of two characters"<<endl<<endl;}在類模板外定義成員函數
#include<iostream> using namespace std; template<class numtype> class compare {public:compare(numtype a,numtype b);numtype max();numtype min();private:numtype x,y;} ;template <class numtype>compare<numtype>::compare(numtype a,numtype b){x=a;y=b;}template<class numtype>numtype compare<numtype>::max(){return (x>y)?x:y;}template<class numtype>numtype compare<numtype>::min(){return(x<y)?x:y;}int main(){compare<int> cmp1(3,7);cout<<cmp1.max()<<"is the maximum of two integer numbers"<<endl;cout<<cmp1.min()<<"is the minimum of two integer numbers"<<endl<<endl;compare<float>cmp2(45.78,93.6);cout<<cmp2.max()<<"is the maximum of two float numbers"<<endl;cout<<cmp2.min()<<"is the minimum of two float numbers"<<endl<<endl;compare<char>cmp3('a','A');cout<<cmp3.max()<<" is the maximum of two characters"<<endl;cout<<cmp3.min()<<" is the minimum of two characters"<<endl<<endl;}?
總結
以上是生活随笔為你收集整理的c++学习笔记之类模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Can 总线 收发原理
- 下一篇: c++学习笔记之运算符的重载