c++模板类和模板函数的使用

来源:互联网 发布:美工切图是什么意思 编辑:程序博客网 时间:2024/06/05 00:44
#include<iostream>#include<string>using namespace std;/**类模板:*/template <class T1,class T2>class Student{    private:        T1 age;        T1 salery;        T2 name;        T2 address;    public:        Student();        Student(T1 age,T1 salery,T2 name,T2 address);        Student(const Student<T1,T2> &tempStu);        void showInfo();        Student<T1,T2> operator+(Student<T1,T2> temp);//this+temp        Student<T1,T2> operator++();//++Stu;        Student<T1,T2> operator--(int i);//Stu--};/**模板类成员函数的定义:*///如果在类体内实现函数,则不用加template<class T1,class T2>//如果在类体外实现函数,则必须每个函数前都要加template<class T1,class T2>template <class T1,class T2>Student<T1,T2>::Student(){//无参构造函数}template <class T1,class T2>Student<T1,T2>::Student(T1 age,T1 salery,T2 name,T2 address){//有参构造函数    this->address=address;    this->age=age;    this->name=name;    this->salery=salery;}template <class T1,class T2>Student<T1,T2>::Student(const Student<T1,T2> &tempStu){//拷贝构造函数    this->name=tempStu.name;    this->address=tempStu.address;    this->age=tempStu.age;    this->salery=tempStu.salery;}template<class T1,class T2>void Student<T1,T2>::showInfo(){//Student的成员函数    cout<<endl;    cout<<"name:"<<name<<endl;    cout<<"age:"<<age<<endl;    cout<<"address:"<<address<<endl;    cout<<"salery:"<<salery<<endl;    cout<<endl;}template<class T1,class T2>Student<T1,T2> Student<T1,T2>::operator+(Student<T1,T2> temp){//Student + 运算符重载    Student<T1,T2> t;    t.age=this->age+temp.age;    return t;}template<class T1,class T2>Student<T1,T2> Student<T1,T2>::operator++(){//++Student(运算符在前,则函数形参列表中无参数)    Student<T1,T2> temp;    temp.age=++this->age;    return temp;}template<class T1,class T2>Student<T1,T2> Student<T1,T2>::operator--(int i){//Student--(运算符在后,则函数形参列表中有参数)    Student<T1,T2> temp;    temp.age=this->age--;    return temp;}/**模板函数用法1:先声明,再定义,再使用*/template <typename T>T test(T a,T b);template <typename T>T test(T a,T b){    return a+b;}/**模板函数用法2:声明时就定义,再使用*/template <typename T>void test2(T a){    cout<<"a*a="<<a*a<<endl;}int main(){    /**模板类的使用:*/    Student<int,string> stu1(22,3400,"YunNan","liming");    stu1.showInfo();    ++stu1;    cout<<"++stu1:"<<endl;    stu1.showInfo();    Student<int,string> stu2(33,4000,"HeBei","xiaoming");    stu2.showInfo();    stu2--;    cout<<"stu2--:"<<endl;    stu2.showInfo();    Student<int,string> stu3=stu1+stu2;    cout<<"stu1+stu2:"<<endl;    stu3.showInfo();    /**模板函数的使用:*/    cout<<"Result:"<<test(2.4,3.5)<<endl;    cout<<"Result:"<<test(2,3)<<endl;    test2(3);//T is int    test2(2.3);//T is float    return 0;}

0 0
原创粉丝点击