目录
1 类模板与继承
2 类模板成员函数类外实现
3 类模板分文件编写
4 类模板友元
5 用模板类写一个数组
运行结果
代码
类模板与继承
·看图推断,son
x; int先传给子类的T1,string传给子类的T2,而T2是父类的T。 ·父类是类模板,子类要明确标明父类T的数据类型。
类模板成员函数类外实现
加模板参数列表
类模板分文件编写
类模板文件.hpp(约定好写hpp)
源文件.cpp
类模板友元
建议在类内实现
用模板类写一个数组
运行结果
(1)数组操作-整型
(2)数组操作-类
(3)数组“=”
(1)类中不能调用类里写好的成员函数
(2)运算符重载=和拷贝构造函数 在函数大部分相似。运算符重载要先析构对象和返回对象指针。
代码
源.cpp
#includeusing namespace std; //#include #include"类模板.hpp" class Student { public: Student() {}; Student(int age_) { this->age = age_; } int age; }; void Print_Arr(MyArray &arr) { for (int i = 0; i < arr.get_size(); i++) { cout << arr[i].age << endl; } } void test() { cout << "普通构造" << endl; MyArray stu(2); Student a(18); Student b(28); Student c(38); stu.insert(a); stu.insert(b); stu.insert(c); stu[1] = stu[0];//把28赋值给18的 Print_Arr(stu); } int main() { test(); } 类模板.hpp
#includeusing namespace std; #include template class MyArray { T* p;//堆区开辟的数组 int Capacity;//数组容量 int size;//数组大小 public: //构造 MyArray(int cap) { this->Capacity = cap; this->size = 0; this->p = new T[this->Capacity]; cout << "MyArray的构造函数" << endl; } //拷贝构造 MyArray(const MyArray &arr) { this->Capacity = arr.Capacity; this->size = arr.size; this->p = new T[this->Capacity]; for (int i = 0; i < this->size; i++) { this->p[i] = arr.p[i]; } cout << "MyArray的拷贝构造函数" << endl; } //运算符重载“=” MyArray& operator=(const MyArray& arr) { if (this->p != NULL) { delete[] this->p; this->p = NULL; this->size = 0; this->Capacity = 0; } this->Capacity = arr.Capacity; this->size = arr.size; this->p = new T[this->Capacity]; for (int i = 0; i < this->size; i++) { this->p[i] = arr.p[i]; } cout << "MyArray的运算符重载函数" << endl; return *this; } //析构 ~MyArray() { if (this->p != NULL) { delete[] this->p; this->p = NULL; } cout << "MyArray的析构函数" << endl; } //数组操作 //尾插法 void insert(const T &val) { if (this->size == this->Capacity) { cout << "尾增法:已满" << endl; return; } this->p[this->size] = val; this->size++; } //尾删法 void pop() { if (this->size == 0) { cout << "尾删法:无元素" << endl; return; } this->size--; } T& operator[](int index){ return this->p[index]; } //遍历 void all() { for (int i = 0; i < this->size; i++) cout << this->p[i] << endl; } int get_size() { return this->size; } int get_capacity() { return this->Capacity; } };



