学习C++时候写的一个简单Array类

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;
}

?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值