您的位置:首页 > 理论基础 > 数据结构算法

数据结构练习(14)含有指针成员的类的拷贝

2012-12-12 17:01 211 查看
http://zhedahht.blog.163.com/blog/static/25411174200722710364233/

上次面试就被问到copy constructor,无奈C++白痴了,这两天狂啃C++ primer和JAVA的时候感觉很多问题似曾相识。

C++果然很强大,用起来神清气爽,是时候入门C++了!

另外看到了stackoverflow上面一个关于unsigned的讨论:

http://stackoverflow.com/questions/2099830/unsigned-keyword-in-c

#include <iostream>
using namespace std;

template <typename T> class Array
{
public:
Array(unsigned arraysize) : data(0), size(arraysize)
{
if (size > 0)
data = new T[size];
}
Array(const Array& copy) : data(0), size(copy.size)
{
if (size > 0)
{
data = new T[size];
for (unsigned i = 0; i < size; ++i)
setvalue(i, copy.getvalue(i));
}
}
const Array& operator = (const Array& copy)
{
if (this == ©)
return *this;

if (data != NULL)
{
delete []data;
data = NULL;
}

size = copy.size;
if (size > 0)
{
data = new T[size];
for (unsigned i = 0; i < size; ++i)
setvalue(i, copy.getvalue(i));
}
}
~Array()
{
if (data)
delete []data;
}
void setvalue(unsigned index, const T& value)
{
if (index < size)
data[index] = value;
}
T getvalue(unsigned index) const
{
if (index < size)
return data[index];
else
return T();
}

private:
T* data;
unsigned size;
};

int main()
{
Array<int> a(10);
Array<int> b(10);
b = a;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: