C++ 模板类定义与声明

来源:互联网 发布:联通软件研究院待遇 编辑:程序博客网 时间:2024/05/21 15:50

#pragma once

#ifndef GRID_H
#define GRID_H

template <typename T>
class Grid
{
public:
    Grid(int inWidth = kDefaultWidth, int inHeight = kDefaultHeight);
    Grid(const Grid<T>& src);
    ~Grid();
    Grid<T>& operator=(const Grid<T>& rhs);
    void setElementAt(int x, int y, const T& inElem);
    T& getElementAt(int x, int y);
    const T& getElementAt(int x, int y) const;
    int getHeight() const {return mHeight;}
    int getWidth() const {return mWidth;}
    static const int kDefaultWidth = 10;
    static const int kDefaultHeight = 10;

protected:
    void copyFrom(const Grid<T>& src);
    T** mcells;
    int mHeight,mWidth;
};

template <typename T>
const int Grid<T>::kDefaultHeight;

template <typename T>
const int Grid<T>::kDefaultWidth;

template <typename T>
Grid<T>::Grid(int inWidth, int inHeight):mWidth(inWidth),mHeight(inHeight)
{
    this->mcells = new T* [this->mWidth];
    for(int i = 0; i < this->mHeight; i++)
    {
        this->mcells[i] = new T[this->mHeight];
    }
}

template <typename T>
Grid<T>::Grid(const Grid<T>& src)
{
    copyFrom(src);
}

template <typename T>
Grid<T>::~Grid()
{
    for(int i = 0; i < this->mWidth; i++)
    {
        delete[] mcells[i];
    }

    delete[] mcells;
}

template <typename T>
void Grid<T>::copyFrom(const Grid<T>& src)
{
    int i, j;
    this->mWidth = src.mWidth;
    this->mHeight = src.mHeight;

    this->mcells = new T* [mWidth];
    for(i = 0; i < mWidth; i++)
    {
        this->mcells[i] = new T [this->mHeight];
    }

    for(i = 0; i < mWidth; i++)
    {
        for(j = 0; j < mHeight; j++)
        {
            this->mcells[i][j] = src[i][j];
        }
    }
}

template <typename T>
Grid<T>& Grid<T>::operator=(const Grid<T>& rhs)
{
    //check for self-assignment;
    if(this == &rhs)
    {
        return (*this);
    }
    //Free the old memory
    for(int i = 0; i < mWidth; i++)
    {
        delete [] mcells[i];
    }

    delete[] mcells;

    //copy the new memory
    copyFrom(rhs);

    return (*this);
}

template <typename T>
void Grid<T>::setElementAt(int x, int y, const T& inElem)
{
    this->mcells[x][y] = inElem;
}

template <typename T>
T& Grid<T>::getElementAt(int x, int y)
{
    retunrn (this->mcells[x][y]);
}

template <typename T>
const T& Grid<T>::getElementAt(int x, int y) const
{
    retunrn (this->mcells[x][y]);
}


#endif // GRID_H
 注意:C++ 模板类定义与声明写在同一个文件中,不然编译通不过。

 

main函数中的调用:Grid<int> myIntGrid;