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;
- 模板类定义与声明
- C++ 模板类的声明与定义
- C++ 模板类定义与声明
- C++ 模板类定义与声明
- 模板类的定义与声明
- C++ 模板类定义与声明
- C++模板类声明与定义
- c++类模板的声明与定义
- 模板的声明与定义
- 模板类声明和定义
- 类模板声明与定义为什么不能分离
- 模板类中friend函数的声明与定义
- C/C++定义与声明
- C/C++ 声明与定义
- C语言定义与声明
- C/C++定义与声明
- C中的声明与定义
- C语言定义与声明
- 端口映射帮助文档
- 【转】8个高质量图标的最佳搜索引擎
- 常用短距离无线通信优缺点的纵横比较
- Java容器类List、ArrayList、Vector及map、HashTable、HashMap的区别与用法 - [Java|技术相关]
- [转]21天教你学会C++
- C++ 模板类定义与声明
- 利用apache+php+mysql安装ucenter
- 爆笑:把女友升级为老婆时发生的BUG!!!
- jvm初始化一个类的六种情形
- 传智播客-ejb3(4)-MDB机制
- javascript:void(0)PK#
- 传智播客-spring2.5(1)-IoC与bean的实例化、轻量级和重量级之分
- 使用opencv显示openni获取的图像
- 传智播客-spring2.5(2)-模拟不采用框架情况下AOP的实现