array.h
类接口
// Class automatically generated by Dev-C++ New Class wizard
/*
?* 数组的抽象数据类型,可以实现:
?* 1、下标准范围检查
?* 2、下标运算
?* 3、数组的赋值
?* 4、数组比较
?* 5、数组的输入/输出
?* 6、数组知道自身的大小
?*/
?
#ifndef ARRAY_H
#define ARRAY_H
#include
using namespace std;
class Array
{
?friend ostream &operator<<(ostream &,const Array &);//输出
?friend istream &operator>>(istream &,Array &);?//输入
?public:
???? int check();
??Array(int arraySize=10);
??Array(const Array &);
??~Array();
??int getSize() const;?//返回数组大小
??int &operator[](int);?//下标运算
? ??const Array &operator= (const Array &) ;//赋至
? ??const int operator!=(const Array &) const;?//不等?
? ??const int operator==(const Array &) const;?//不等?
?private:
???? int size;?// 数组的大小
???? int *ptr;?// 指向数组的第一个元素的指针
};
#endif // ARRAY_H
?
?
?
//类实现
// Class automatically generated by Dev-C++ New Class wizard
#include "array.h" // class's header file
#include
using namespace std;
// class constructor
Array::Array(int arraySize)
{
?size = arraySize;
?ptr = new int[size];
?assert(ptr!=0);
?memset(ptr,0,size*sizeof(int));
}
// 拷贝构造函数
Array::Array(const Array &init)
{
?size = init.size;
?ptr = new int[size];
?assert(ptr!=0);
?memset(ptr,0,size*sizeof(int));
}
// class destructor
Array::~Array()
{
?delete [] ptr;
}
//数组范围检查
int Array::check()
{
?return 1;???
}
//取得数组大小
int Array::getSize() const
{
??? return size;
}
istream &operator>> (istream &input,Array &a)
{
?for(int i=0;i
??input>>a.ptr[i];
?return input;
}
//输出
ostream &operator<< (ostream &output,const Array &a)
{
?for(int i=0;i
??output<
<<' ';
?return output;
}
//下标
int &Array::operator[](int index)
{
??? if(index<0||index>size) index = 0;
?return ptr[index];
}
//重载 =?
const Array &Array::operator=(const Array &right)
{
??? if(&right!=this)
??? {
??????? if(size!=right.size)?//如果空间不同,则重新分配
??????? {
??????? ?delete [] ptr;
??????? ?size = right.size;
??????? ?ptr = new int[size];
?? ???????? assert(ptr!=0);
???? ?}
??? ?memcpy(ptr,right.ptr,size*sizeof(int));
??? }
??? return *this;
}
const int Array::operator!=(const Array &right) const
{
??? if (size!=right.size) return 1;
??? for(int i=0;i
??? ?if(ptr[i]!=right.ptr[i])
??? ??return 1;
??? return 0;
}
const int Array::operator==(const Array &right) const
{
??? if (size==right.size) return 1;
??? for(int i=0;i
??? ?if(ptr[i]!=right.ptr[i])
??? ??return 0;
??? return 1;
}
?