在GameBoard.h文件里:
// // Created by Administrator on 2019/2/6. // #ifndef GAMEBOARDTEMPLATE_GAMEBOARD_H #define GAMEBOARDTEMPLATE_GAMEBOARD_H #include<iostream> #include <vector> template<typename T , size_t WIDTH = 10 , size_t HEIGHT = 10> class GameBoard { public: GameBoard() : mCells(){} virtual ~GameBoard(); template<typename E , size_t WIDTH1 , size_t HEIGHT1> GameBoard(const GameBoard<E,WIDTH1,HEIGHT1>& src); template<typename E , size_t WIDTH1 , size_t HEIGHT1> GameBoard<T,WIDTH,HEIGHT>& operator = (const GameBoard<E,WIDTH1,HEIGHT1>& rhs); void setElemtAt(size_t x,size_t y,const T& src); const T& getElemtAt(size_t x, size_t y); public: size_t getWidth(){return mWidth;} size_t getHeight(){return mHeight;} private: size_t mWidth,mHeight; template<typename E , size_t WIDTH1 , size_t HEIGHT1> void copyFrom(const GameBoard<E,WIDTH1,HEIGHT1>& src); T mCells[WIDTH][HEIGHT]; }; #endif //GAMEBOARDTEMPLATE_GAMEBOARD_H
在GameBoard.cpp里
#include "GameBoard.h" template<typename T , size_t WIDTH , size_t HEIGHT> GameBoard<T,WIDTH,HEIGHT>::~GameBoard() { } template<typename T , size_t WIDTH , size_t HEIGHT> template<typename E , size_t WIDTH1 , size_t HEIGHT1> GameBoard<T,WIDTH,HEIGHT>::GameBoard(const GameBoard<E,WIDTH1,HEIGHT1>& src) { copyFrom(src); } template<typename T , size_t WIDTH , size_t HEIGHT> template<typename E , size_t WIDTH1 , size_t HEIGHT1> GameBoard<T,WIDTH,HEIGHT>& GameBoard<T,WIDTH,HEIGHT>::operator = (const GameBoard<E,WIDTH1,HEIGHT1>& rhs) { copyFrom(rhs); return *this; } template<typename T , size_t WIDTH , size_t HEIGHT> void GameBoard<T,WIDTH,HEIGHT>::setElemtAt(size_t x,size_t y,const T& src) { mCells[x][y] = src.getElemtAt(x,y); } template<typename T , size_t WIDTH , size_t HEIGHT> const T& GameBoard<T,WIDTH,HEIGHT>::getElemtAt(size_t x, size_t y) { return mCells[x][y]; } template<typename T , size_t WIDTH , size_t HEIGHT> template<typename E , size_t WIDTH1 , size_t HEIGHT1> void GameBoard<T,WIDTH,HEIGHT>::copyFrom(const GameBoard<E,WIDTH1,HEIGHT1>& src) { for(size_t i = 0;i < WIDTH;++i) { for(size_t j = 0;j < HEIGHT;++j) { if(i <= WIDTH1 && j <= HEIGHT1) { mCells[i][j] = src.mCells[i][j]; } else { mCells[i][j] = 0; } } } }
编写复制构造函数时,编译器不会自动生成默认的构造函数,因此必须手动添加一个默认的构造函数