C++方法模板

template 
class Grid
{
public:
	Grid(size_t inWidth = kDefaultWidth, size_t inHeight = kDefaultHeight);
	Grid(const Grid& src);
	template 
	Grid(const Grid& src);
	virtual ~Grid();

	Grid& operator=(const Grid& rhs);
	template 
	Grid& operator=(const Grid& 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& src);
	template 
	void copyFrom(const Grid& src);

	T** mCells;
	size_t mWidth, mHeight;
};

template 
Grid::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 
Grid::Grid(const Grid& src)
{
	copyFrom(src);
}

template 
Grid::~Grid()
{
	for (size_t i = 0; i < mWidth; i++) {
		delete[] mCells[i];
	}
	delete[] mCells;
	mCells = nullptr;
}

template 
void Grid::copyFrom(const Grid& 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 
Grid& Grid::operator=(const Grid& 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 
void Grid::setElementAt(size_t x, size_t y, const T& inElem)
{
	mCells[x][y] = inElem;
}

template 
T& Grid::getElementAt(size_t x, size_t y)
{
	return mCells[x][y];
}

template 
const T& Grid::getElementAt(size_t x, size_t y) const
{
	return mCells[x][y];
}

template 
template 
Grid::Grid(const Grid& src)
{
	copyFrom(src);
}

template 
template 
void Grid::copyFrom(const Grid& 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 
template 
Grid& Grid::operator=(const Grid& rhs)
{
	for (size_t i = 0; i < mWidth; i++) {
		delete[] mCells[i];
	}
	delete[] mCells;
	mCells = nullptr;

	copyFrom(rhs);

	return *this;
}

你可能感兴趣的:(c++)