1.关系运算符重载
2.类型转换函数重载
3.转换构造函数
4.函数模板
5.显式实例化
6.类模板外定义模板函数
1.关系运算符重载
==关系运算符重载== //直接(按分数)比较两个对象 #includeusing namespace std; class Student { public: friend ostream& operator<< (ostream& os,const Student& st); friend istream& operator>> (istream& is, Student& st); friend bool operator == (const Student& st1,const Student& st2); friend bool operator != (const Student& st1,const Student& st2); friend bool operator > (const Student& st1,const Student& st2); friend bool operator < (const Student& st1,const Student& st2); private: int id; double score; }; ostream& operator<< (ostream& os,const Student& st) { os <<"id:"< > (istream& is,Student& st) { is >> st.id >> st.score; return is; } bool operator == (const Student& st1,const Student& st2) { return st1.score == st2.score; } bool operator != (const Student& st1,const Student& st2) { return !(st1.score == st2.score); } bool operator > (const Student& st1,const Student& st2) { return (st1.score > st2.score); } bool operator < (const Student& st1,const Student& st2) { return (st1.score < st1.score); } int main() { Student st1,st2; cout<<"请输入两名学生的ID和score:"< >st1>>st2; if (st1 > st2) { cout<<"st1分数高于st2"< 2.类型转换函数重载
==类型转换函数重载== #includeusing namespace std; class bian { private: int m,n; public: bian(int m1,int n1):m(m1),n(n1){} void show() { cout<<"bb:"< (m); } }; int main() { bian bb(69,96); bb.show(); char ch = bb; cout< 3.转换构造函数
==转换构造函数== #includeusing namespace std; class jie { private: int m,n; public: jie(int a, int b):m(a),n(b){} jie(double c) { cout<<"把m转换成字符型,并给n一个值"< (c); n = 0; } void show() { cout< 4.函数模板
==函数模板== //目的 函数运行与类型无关 #includeusing namespace std; template T add(T x,T y) { return x+y; } int main() { cout< 5.显式实例化
==显式实例化== //指定参数类型,便于不同类型数据类型相加 #includeusing namespace std; template T add(T x,T y) { return x+y; } template int add (int x,int y); int main() { cout<(3.1415,'a')< 6.类模板外定义模板函数
==类模板外定义模板函数== #includeusing namespace std; template class Fly { private: int size; T* str; public: Fly(T fly[],int s); void show(); }; //类模板外定义成员函数 template Fly ::Fly(T fly[],int s) { str = new T[s]; size = s ; for(int i = 0;i < size; i++) { str[i] = fly[i]; } } template void Fly ::show() { for(int k = 0; k F1(ffly,5); F1.show(); int jfly[]={5,2,1,1314}; //创建类模板对象 Fly F2(jfly,4); F2.show(); return 0; }



