StaticArray.cpp代码示例
#include <iostream>
using namespace std;
template <typename T, int N>
class StaticArray
{
private:
T* m_array;
T m_space[N];
public:
StaticArray()
{
m_array = m_space;
}
//拷贝构造函数
StaticArray(const StaticArray<T,N>& obj)
{
if(m_array = m_space)
{
for(int i = 0; i < N; i++)
{
m_space[i] = obj.m_space[i];
}
}
}
//重载赋值操作符
StaticArray<int,N>& operator = (const StaticArray<T,N>& obj)
{
//如果不是自赋值
if(this != &obj)
{
for(int i = 0; i < N; i++)
{
m_space[i] = obj.m_space[i];
}
}
return *this;
}
//重载数组访问操作符
T& operator [] (int i)
{
if((0 <= i) && (i < length()))
{
return m_array[i];
}
}
//代码复用用非const版本实现const版本
T operator [](int i) const
{
return (const_cast<T&>(*this))[i];
}
int length() const
{
return N;
}
};
int main()
{
StaticArray<int, 5> sa1;
for(int i = 0; i < sa1.length(); i++)
{
sa1[i] = i * i;
}
for(int i = 0; i < sa1.length(); i++)
{
cout << sa1[i] << endl;
}
cout << endl;
StaticArray<int, 5> sa2;
sa2 = sa1;
for(int i = 0; i < sa2.length(); i++)
{
cout <<sa2[i] << endl;
}
return 0;
}
运行截图