C++类模版1
类模版作用:
- 建立一个通用类,类中的成员,数据结构可以不具体制定,用一个虚拟的类型来代表
语法:
template<typename T>
类
#include <iostream>
using namespace std;//类模版
template<typename NameType,typename AgeType>
class Person{public://构造函数Person(NameType name,AgeType age){this->m_Name=name;this->m_Age=age;}void showPerson(){cout<<"name: "<<this->m_Name<<endl;cout<<"age: "<<this->m_Age<<endl;}//但是这两个类型是不一样的,要是这两个类型是一样的,只用一个T就够了NameType m_Name;AgeType m_Age;};void test01()
{//类模版的使用//<>表示的是模版的参数列表Person<string,int> p1("孙悟空",999);p1.showPerson();
}int main()
{test01();return 0;
}
类模版与函数模版语法相似,在声明模版template后面加类,此类称为类模版。
类模版与函数模版区别
1.类模版没有自动类型推导的使用方式
2.类模版在模版参数列表中可以有默认参数
类模版中的成员函数创建时机
- 普通类中的成员函数一开始就可以创建
- 类模版中的成员函数在调用时才创建
#include <iostream>
using namespace std;class Person1{public:void showPerson1(){cout<<"Person1 show"<<endl;}
};class Person2{public:void showPerson2(){cout<<"Person2 show"<<endl;}
};template <typename T>
class MyClass{public:T obj;//类模版中的成员函数void func1(){obj.showPerson1();}void showPerson2(){obj.showPerson2();}
};int main() {}
为什么这个代码跑得通,因为这两个成员函数,只要没有调用,就不会被创建的,为什么不会被创建。
#include <iostream>
using namespace std;class Person1{public:void showPerson1(){cout<<"Person1 show"<<endl;}
};class Person2{public:void showPerson2(){cout<<"Person2 show"<<endl;}
};template <typename T>
class MyClass{public:T obj;//类模版中的成员函数void func1(){obj.showPerson1();}void func2(){obj.showPerson2();}
};void test01(){MyClass<Person1> m;m.func1(); // 调用 Person1 的成员函数m.func2();}int main() {test01();return 0;}
但是下面这个就会出错。
总结:类模版中的成员函数并不是一开始就创建的,在调用时才创建。