类模板碰到继承问题
-
基类如果是模板类,必须让子类告诉编译器 基类中的T到底是什么类型
-
如果不告诉,那么无法分配内存,编译不过
-
利用参数列表
class Child :public Base<int>
#include<iostream>using namespace std;template<class T>class Base{public:T m_A;};//Child继承于Base必须告诉base中的T的类型,否则T无法分配内存class Child :public Base<int>{};//Child2也是模板类template<class T1,class T2>class Child2 :public Base<int>{public:Child2(){cout << typeid(T1).name ()<< endl;cout << typeid(T2).name ()<< endl;}public:T1 m_B;};void test01(){Child2<int, double >child;//由用户来指定类型}int main(){test01();system("pause");return 0;}
类模板类外实现
-
template<class T1 ,class T2>
Person<T1, T2>::Person(T1 name, T2 age)#include<iostream>#include<string>using namespace std;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;};//类外实现成员函数template<class T1 ,class T2>Person<T1, T2>::Person(T1 name, T2 age){this->m_Name = name;this->m_Age = age;}template<class T1, class T2>void Person<T1, T2>::showPerson(){cout << "姓名" << this->m_Name << "年龄" << this->m_Age << endl;}void test01(){Person <string,int >p1("Mt", 100);p1.showPerson();}int main(){test01();system("pause");return 0;}
类模板与友元函数
友员函数类内实现
#include<iostream>
#include<string>
using namespace std;template<class T1,class T2>class Person
{//友员函数类内实现friend void printPerson(Person<T1,T2>&p){cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;}
public:Person(T1 name, T2 age){this->m_Name = name;this->m_Age = age;}private:T1 m_Name;T2 m_Age;
};void test01(){Person<string, int >p("Tom", 10);printPerson(p);
}int main()
{test01();system("pause");return 0;
}
友员函数类内实现
#include<iostream>
#include<string>
using namespace std;//让编译器提前看到printPerson声明
template<class T1, class T2>class Person;
template<class T1, class T2>void printPerson(Person<T1, T2>&p);template<class T1, class T2>class Person
{//友员函数类内实现 利用空参数列表 告诉编译器 模板函数声明friend void printPerson<>(Person<T1, T2>&p); //普通函数 声明/*{cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;}*/
public:Person(T1 name, T2 age){this->m_Name = name;this->m_Age = age;}private:T1 m_Name;T2 m_Age;
};//类外实现
template<class T1,class T2>void printPerson(Person<T1, T2>&p)
{cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
}void test01(){Person<string, int >p("Tom", 10);printPerson(p);
}int main()
{test01();system("pause");return 0;
}