您的位置:首页 > 编程语言

《CPlusPlusPrimer》第二章编程源码——Array模板简单实现

2011-09-07 19:02 351 查看
array.h

#ifndef _CPlusPlusPrimer_Array
#define _CPlusPlusPrimer_Array

// 定义域名空间
namespace Icanth_CPlusPlus_Primer
{
template<class elemType>
class Array
{
public:
// 把元素类型参数化
explicit Array(int size = DefaultArraySize);
Array(elemType* array, int array_size);
Array(const Array& rhs);
virtual ~Array() { delete [] ia; }
// 第二个只能调用其它const成员函数,及不能对数据成员进行修改;
// 获得对常量对象(此时为const Array &对象)的const成员函数.
bool operator==(const Array &) const;
bool operator!=(const Array &) const;
Array& operator=(const Array &);
int size() const { return _size; }
virtual elemType& operator[](int index) { return ia[index]; }
protected:
static const int DefaultArraySize = 12; // 静态常量整型
int _size; // 函数名不能与变量名相同
elemType* ia;
};
}

#endif


array.cpp

#include "array.h"

using namespace Icanth_CPlusPlus_Primer;

template<class elemType>
Array<elemType>::Array(int size = DefaultArraySize)
{
ia = new elemType[size];

for(int i = 0; i < size; i++)
{
*(ia + i) = 0;
}
_size = size;
}

template <class elemType>
Array<elemType>::Array(elemType* array, int array_size)
{
ia = new elemType[array_size];

for(int i = 0; i < array_size; i++)
{
*(ia + i) = array[i];
}
_size = array_size;
}

template <class elemType>
bool Array<elemType>::operator==(const Array &arr) const
{
int i = 0;
bool rslt = false;

if((size() == 0) || (size() != arr.size()))
{
rslt = false;
}
else
{
while((i < size()) && (ia[i] && arr.ia[i]))
{
i++;
}
rslt = (i == size()) ? true : false;
}

return rslt;
}

template <class elemType>
bool Array<elemType>::operator!=(const Array &arr) const
{
return !(this==arr);
}

template <class elemType>
Array<elemType>& Array<elemType>::operator=(const Array &arr)
{
Array<elemType> new_arr(arr.ia, arr.size());

delete this;
this = new_arr;

return this;
}


test.cpp

// 只有包含array.cpp文件才能使用模板类,
// 而只包含#include "array.h"则不行。详解见STL原理。
#include "array.cpp"
#include <iostream>

using namespace std; // 使用标准库域名空间
namespace ICP = Icanth_CPlusPlus_Primer; // 将域名空间Icanth_CPlusPlus_Primer缩写成ICP

int main()
{
using ICP::Array; // 使用ICP下的Array类
const int array_size = 3;
int array[array_size] = {1, 2, 3};
Array<int> intArray(3);
Array<int> intArray2(array, array_size);

cout << "the value of intArray2[2]:" << intArray2[2] << endl;

intArray2[2] = 3;
cout << "the value of intArray2[2] after excuting intArray[2] = 3 is:" << intArray2[2] << endl;

cout << "before the envalution to intArray1, the result of comparing intArray1 and intArray2 is:" << (intArray == intArray2) << endl;

intArray[0] = intArray2[0];
intArray[1] = intArray2[1];
intArray[2] = intArray2[2];

cout << "afther the envalution to intArray1, the result of comparing intArray1 and intArray2 is:" << (intArray == intArray2) << endl;

return 0;
}


运行截图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: