数组类的创建(上):StaticArray
Posted 学习只为旅行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组类的创建(上):StaticArray相关的知识,希望对你有一定的参考价值。
线性表可能被当成数组乱用!
数组类创建的意义,就是替代C++原生数组!
#ifndef ARRAY_H
#define ARRAY_H
#include "Object.h"
#include "Exception.h"
namespace DragonLib {
template <typename T>
class Array : public Object
{
protected:
T* m_array;
public:
virtual bool set(int i,const T& e) //O(1)
{
bool ret = ((0<=i) && (i<length()));
if(ret)
{
m_array[i] = e;
}
return ret;
}
virtual bool get(int i,T& e) const //O(1)
{
bool ret = ((0<=i) && (i<length()));
if(ret)
{
e=m_array[i];
}
return ret;
}
T& operator [] (int i) //O(1)
{
if((0<=i) && (i<length()))
{
return m_array[i];
}
else
{
THROW_EXCEPTION(IndexOutOfBoundsException,"Parameter i is invalid...");
}
}
T operator [] (int i) const //O(1)
{
return (const_cast<Array<T>&>(*this))[i];
}
virtual int length() const=0;
};
}
#endif // ARRAY_H
#ifndef STATICARRAY_H
#define STATICARRAY_H
#include "Array.h"
namespace DragonLib {
template <typename T,int N>
class StaticArray : public Array<T>
{
protected:
T m_space[N];
public:
StaticArray()//O(1)
{
this->m_array=m_space;
}
StaticArray(const StaticArray<T,N>& obj)//O(n)
{
this->m_array=m_space;
for(int i=0;i<N;i++)
{
m_space[i]=obj.m_space[i];
}
}
StaticArray<T,N>& operator = (const StaticArray<T,N>& obj)//O(n)
{
if(this!=&obj)
{
for(int i=0;i<N;i++)
{
m_space[i]=obj.m_space[i];
}
}
return *this;
}
int length() const//O(1)
{
return N;
}
};
}
#endif // STATICARRAY_H
以上是关于数组类的创建(上):StaticArray的主要内容,如果未能解决你的问题,请参考以下文章