类模板基础
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; #include <string> template<class NAMETYPE, class AGETYPE = int > //类模板中 可以有默认参数 class Person { public: Person(NAMETYPE name, AGETYPE age) { this->m_Name = name; this->m_Age = age; } void showPerson() { cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl; } NAMETYPE m_Name; AGETYPE m_Age; }; void test01() { //类模板和函数模板区别: //1、类模板不可以使用自动类型推导,只能用显示指定类型 //2、类模板中 可以有默认参数 //Person p1("孙悟空", 100); Person<string > p1("孙悟空", 100); p1.showPerson(); } int main(){ test01(); system("pause"); return EXIT_SUCCESS; }
类模板中的成员函数创建时机
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; class Person1 { public: void showPerson1() { cout << "Person1 show 调用" << endl; } }; class Person2 { public: void showPerson2() { cout << "Person2 show 调用" << endl; } }; //类模板中的成员函数 并不是一开始创建的,而是在运行阶段确定出T的数据类型才去创建 template<class T> class MyClass { public: void func1() { obj.showPerson1(); } void func2() { obj.showPerson2(); } T obj; }; void test01() { MyClass <Person2> p1; //p1.func1(); p1.func2(); } int main(){ test01(); system("pause"); return EXIT_SUCCESS; }
类模板做函数参数
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; #include <string> template<class T1, class T2> //类模板中 可以有默认参数 class Person { public: Person(T1 name, T2 age) { this->m_Name = name; this->m_Age = age; } void showPerson() { cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl; } T1 m_Name; T2 m_Age; }; //1、指定传入类型 void doWork(Person <string, int>&p) { p.showPerson(); } void test01() { Person <string, int>p("孙悟空", 999);//这是类模板创建对象操作 doWork(p); } //2、参数模板化 template<class T1, class T2> void doWork2(Person <T1, T2>&p) { cout << "T1数据类型: " << typeid(T1).name() << endl; cout << "T2数据类型: " << typeid(T2).name() << endl; p.showPerson(); } void test02() { Person<string, int>p("猪八戒", 998); doWork2(p); } //3、整个类 模板化 template<class T> void doWork3( T &p) { cout << "T的数据类型: " << typeid(T).name() << endl; p.showPerson(); } void test03() { Person<string, int>p("唐僧", 10000); doWork3(p); } int main(){ //test01(); //test02(); test03(); system("pause"); return EXIT_SUCCESS; }
类模板继承相关问题
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; template<class T> class Base { public: T m_A; }; //必须要指定出父类中的T数据类型,才能给子类分配内存 class Son :public Base<int> { }; template<class T> class Base2 { public: T m_A; }; template<class T1 ,class T2> class Son2 :public Base2<T2> { public: Son2() { cout << typeid(T1).name() << endl; cout << typeid(T2).name() << endl; } T1 m_B; }; void test01() { Son2 <int, double> s; } int main(){ test01(); system("pause"); return EXIT_SUCCESS; }
标签:cout,--,void,c++,class,template,泛型,public,模板 From: https://www.cnblogs.com/chaojibaidu/p/17537794.html