学了上节的知识,我们再来看看类模板
C++函数模板
https://blog.csdn.net/qq_58665528/article/details/122424591
写一个可扩展的动态数组
//func.h #pragma once #include <iostream> template<typename T> class Array; //一定要先写类声明 template<typename T> std::ostream& operator<<(std::ostream& out, const Array<T>& array); //写在类声明后面 template<typename T> class Array { private: T* m_address; //数组首地址 int m_size; //数组现有元素个数 int m_capacity; //数组容量 friend std::ostream& operator<< <>(std::ostream& out, const Array<T>& array); //友元重载运算符函数 //如果<<是函数模板型重载就要写成<<<> public: Array(int capacity = 0); //构造函数 void add(T value); //向数组增加一个元素 T get(int index); //返回当前下标的元素 int size(); //返回数组现有元素个数 T operator[](int index); //重载运算符[] ~Array(); //析构函数 }; template<typename T> Array<T>::Array(int capacity) { this->m_size = 0; this->m_capacity = (capacity > 0) ? capacity : 10; this->m_address = new T[this->m_capacity]; } template<typename T> void Array<T>::add(T value) { if (this->m_size < this->m_capacity) { this->m_address[this->m_size++] = value; } else { this->m_capacity += this->m_capacity; T* address = new T[this->m_capacity]; for (int i = 0; i < this->m_size; ++i) { address[i] = this->m_address[i]; } delete[] this->m_address; this->m_address = address; this->m_address[this->m_size++] = value; } } template<typename T> T Array<T>::get(int index) { if (index >= this->m_capacity || index < 0) { throw "数组下标越界"; } return this->m_address[index]; } template<typename T> int Array<T>::size() { return this->m_size; } template<typename T> T Array<T>::operator[](int index) { return this->get(index); } template<typename T> Array<T>::~Array() { if (this->m_address != nullptr) { delete[] this->m_address; this->m_address = nullptr; } } template<typename T> std::ostream& operator<<(std::ostream& out, const Array<T>& array) { out << "["; for (int i = 0; i < array.m_size; ++i) { if (i != 0) out << ", "; out << array.m_address[i]; } out << "]"; return out; }
//main.cpp #include <iostream> #include "func.h" int main(void) { Array<int> a; for (int i = 0; i < 11; ++i) a.add(i); std::cout << a; return 0; }