C++方法模板

来源:互联网 发布:蚁群算法和粒子群算法 编辑:程序博客网 时间:2024/06/15 06:34
template <typename T>class Grid{public:Grid(size_t inWidth = kDefaultWidth, size_t inHeight = kDefaultHeight);Grid(const Grid<T>& src);template <typename E>Grid(const Grid<E>& src);virtual ~Grid();Grid<T>& operator=(const Grid<T>& rhs);template <typename E>Grid<T>& operator=(const Grid<E>& rhs);void setElementAt(size_t x, size_t y, const T& inElem);T& getElementAt(size_t x, size_t y);const T& getElementAt(size_t x, size_t y) const;size_t getHeight() const { return mHeight; }size_t getWith() const { return mWidth; }static const size_t kDefaultWidth = 10;static const size_t kDefaultHeight = 10;protected:void copyFrom(const Grid<T>& src);template <typename E>void copyFrom(const Grid<E>& src);T** mCells;size_t mWidth, mHeight;};template <typename T>Grid<T>::Grid(size_t inWith, size_t inHeight) : mWidth(inWith), mHeight(inHeight){mCells = new T*[mWidth]; for (size_t i = 0; i < mWidth; i++) {mCells[i] = new T[mHeight];}}template <typename T>Grid<T>::Grid(const Grid<T>& src){copyFrom(src);}template <typename T>Grid<T>::~Grid(){for (size_t i = 0; i < mWidth; i++) {delete[] mCells[i];}delete[] mCells;mCells = nullptr;}template <typename T>void Grid<T>::copyFrom(const Grid<T>& src){mWidth = src.mWidth;mHeight = src.mHeight;mCells = new T*[mWidth];for (size_t i = 0; i < mWidth; i++) {mCells[i] = new T[mHeight];}for (size_t i = 0; i < mWidth; i++) {for (size_t j = 0; j < mHeight; j++) {mCells[i][j] = src.mCells[i][j];}}}template <typename T>Grid<T>& Grid<T>::operator=(const Grid<T>& rhs){if (this = &rhs)return (*this);for (size_t i = 0; i < mWidth; i++) {delete[] mCells[i];}delete[] mCells;mCells = nullptr;copyFrom(rhs);return *this;}template <typename T>void Grid<T>::setElementAt(size_t x, size_t y, const T& inElem){mCells[x][y] = inElem;}template <typename T>T& Grid<T>::getElementAt(size_t x, size_t y){return mCells[x][y];}template <typename T>const T& Grid<T>::getElementAt(size_t x, size_t y) const{return mCells[x][y];}template <typename T>template <typename E>Grid<T>::Grid(const Grid<E>& src){copyFrom(src);}template <typename T>template <typename E>void Grid<T>::copyFrom(const Grid<E>& src){mWidth = src.getWith();mHeight = src.getHeight();mCells = new T*[mWidth];for (size_t i = 0; i < mWidth; i++) {mCells[i] = new T[mHeight];}for (size_t i = 0; i < mWidth; i++) {for (size_t j = 0; j < mHeight; j++) {mCells[i][j] = src.getElementAt(i, j);}}}template <typename T>template <typename E>Grid<T>& Grid<T>::operator=(const Grid<E>& rhs){for (size_t i = 0; i < mWidth; i++) {delete[] mCells[i];}delete[] mCells;mCells = nullptr;copyFrom(rhs);return *this;}

0 0
原创粉丝点击