1.模板起源
1.模板的定义
1.针对函数属性模板
//针对函数属性 template <class VOID > VOID print1(int a) { cout << a << endl; }
2.针对数据属性模板
//针对数据属性 template <typename INT,typename FLOAT> void print2(INT a,FLOAT b) { cout << a << b << endl; }
3.main
int main() { print1<void>(1); print2<int,float>(2,3.3); }
结果:
2.模板与重载的结合
1.class MM
class MM { public: MM() {} MM(int age,string name):age(age),name(name) {} int getAge() { return age; } string getName() { return name; } private: int age; string name; };
2.模板与流重载的匹配
template<class XX> void print(XX a) { cout << a << endl; } ostream& operator<<(ostream& out,MM mm) { out << mm.getAge() << mm.getName() << endl; return out; }
3.main
int main() { MM mm[3] = { {12,"女生"},{18,"女神"},{23,"女汉子"} }; cout << mm[0] << mm[1] << mm[2] << endl; return 0; }
结果:
补充:我们可以对流重载使用友元函数,解决无法访问内部类的问题
1.class MM
class MM { //友元类 friend ostream& operator<<(ostream& out, MM mm); private: public: MM() {} MM(int age,string name):age(age),name(name) {} int age; string name; };
2.模板与流重载
template<class XX> void print(XX a) { cout << a << endl; } ostream& operator<<(ostream& out,MM mm) { out << mm.age << mm.name << endl; return out; }
3.main
int main() { MM mm[3] = { {12,"女生"},{18,"女神"},{23,"女汉子"} }; cout << mm[0] << mm[1] << mm[2] << endl; return 0; }
结果:
3.模板类
继承模板类后,成员函数与子类都需要加模板申明,麻烦很少用