在GameBoard.h文件里:
// // Created by Administrator on 2019/2/6. // #ifndef GAMEBOARDTEMPLATE_GAMEBOARD_H #define GAMEBOARDTEMPLATE_GAMEBOARD_H #include<iostream> #include <vector> template<typename T> class GameBoard { public: GameBoard(); GameBoard(size_t inWidth,size_t inHeight); template<typename E> GameBoard(const GameBoard<E>& src); template<typename E> GameBoard<T>& operator = (const GameBoard<E>& rhs); void setElem(size_t x,size_t y,const GameBoard& inElem); T& getElem(size_t x,size_t y); virtual ~GameBoard(); public: static const size_t mDefalutWidth = 10; static const size_t mDefalutHeight = 10; size_t getWidth(){return mWidth;} size_t getHeight(){return mHeight;} private: size_t mWidth,mHeight; std::vector<std::vector<T>> mCells; template<typename E> void copyFrom(const GameBoard<E>& src); void initialContainer(); bool inRange(size_t x,size_t inX) { return x > inX ? false : true; } }; #endif //GAMEBOARDTEMPLATE_GAMEBOARD_H
在GameBoard.cpp文件里:
#include "GameBoard.h" template<typename T> GameBoard<T>::GameBoard() :mWidth(0) ,mHeight(0) { initialContainer(); } template<typename T> GameBoard<T>::GameBoard(size_t inWidth,size_t inHeight) :mWidth(inWidth > mDefalutWidth ? mDefalutHeight : inWidth) ,mHeight(inHeight > mDefalutHeight ? mDefalutHeight : inHeight) { } template<typename T> template<typename E> GameBoard<T>::GameBoard(const GameBoard<E>& src) { copyFrom(src); } template<typename T> template<typename E> GameBoard<T>& GameBoard<T>::operator = (const GameBoard<E>& rhs) { copyFrom(rhs); return *this; } template<typename T> void GameBoard<T>::setElem(size_t x,size_t y,const GameBoard& inElem) { if(!inRange(x,mWidth) || !inRange(y,mHeight)) { throw std::invalid_argument("invalid argument\r\n"); } this->mCells[x][y] = inElem; } template<typename T> T& GameBoard<T>::getElem(size_t x,size_t y) { if(!inRange(x,mWidth) || !inRange(y,mHeight)) { throw std::invalid_argument("invalid argument\r\n"); } return this->mCells[x][y]; } template<typename T> GameBoard<T>::~GameBoard() { } template<typename T> template<typename E> void GameBoard<T>::copyFrom(const GameBoard<E> &src) { mWidth = src.getWidth(); mHeight = src.getHeight(); initialContainer(); for(int i = 0;i < mWidth;++i) { for(int j = 0;j <mHeight;++j) { mCells[i][j] = src.mCells[i][j]; } } } template<typename T> void GameBoard<T>::initialContainer() { mCells.resize(mWidth); for(auto &item : mCells) { item.resize(mHeight); } }
在main()函数体内:
#include <iostream> #include "GameBoard.h" #include "GameBoard.cpp" int main() { GameBoard<int> myIntBoard; GameBoard<double> myDoubleBoard; myDoubleBoard = myIntBoard; return 0; }
会报错这是为什么!
错误是:
required from 'GameBoard<T>& GameBoard<T>::operator=(const GameBoard<E>&) [with E = int; T = double]'
passing 'const GameBoard<int>' as 'this' argument discards qualifiers [-fpermissive]mWidth = src.getWidth();