该项目一共有3个文件,main.cpp、Array.h和Array.cpp。其中main.cpp是测试文件,Array.h包含Array类的定义和成员函数声明。用户仅能修改Array.cpp中的内容,在其中实现Array的成员函数。
Array.h的内容如下
#ifndef _ARRAY_H_
#define _ARRAY_H_
class Array{
private:
enum {SIZE=1000};//该枚举的作用是规定原生数组的尺寸
int data[SIZE]; //被包装的原生数组,可称之为数据的容器
int size; //当前数组的实际元素个数
public:
int getSize()const{return size;}
//4个构造函数
Array();
Array(const Array&rhs);
Array(int const a[],int n);
Array(int count,int value);
/**增删查改*/
//pos位置上插入一个值为value的元素,pos及其后面的元素依次后移
void insert(int pos,int value);
//删除pos位置上的元素,其后的元素依次前移
void remove(int pos);
//返回第pos个位置上的元素值
int at(int pos)const;
//将pos位置上的元素值修改为newValue
void modify(int pos,int newValue);
//显示函数,将数组内容显示输出为一行,且每一个数后面均有一个空格
void disp()const;
};
#endif // _ARRAY_H_
main.cpp的内容如下
#include <iostream>
#include "Array.h"
using namespace std;
int main(){
int n,x;
Array a;
cin>>n;
for(int i=0;i<n;++i){
cin>>x;
a.insert(a.getSize(),x);
}
a.disp();
for(int i=0;i<3&&a.getSize()!=0;++i){
a.remove(0);
}
a.disp();
for(int i=0;i<a.getSize();i+=2){
a.modify(i,a.at(i)*10);
}
a.disp();
return 0;
}
这是我写的,根本没结果,不知道哪里错了,感觉是insert错了
#include <iostream>
#include "Array.h"
using namespace std;
Array::Array()
{
size = 0;
};
Array::Array(const Array&rhs)
{
int i;
for(i=0;i<SIZE;++i)
{
data[i] = rhs.data[i];
}
size = rhs.getSize();
}
Array::Array(int const a[],int n)
{
int i;
for(i=0;i<n;++i)
{
data[i] = a[i];
}
size = n;
}
Array::Array(int count,int value)
{
size = count;
int i;
for(i=0;i<count;++i)
{
data[i] = value;
}
}
void Array::insert(int pos,int value){
data[pos-1]=value;
for(int i=pos;i<size;i++)
data[i]=data[i+1];
}
void Array::remove(int pos){
for(int i=pos;i<size;i++)
{data[i]=data[i+1];}
size=size-1;
}
int Array::at(int pos)const{
return data[pos-1];
}
void Array::modify(int pos,int newValue){
data[pos-1]=newValue;
}
void Array::disp()const{
for(int i=0;i<this->getSize();i++){
cout<<this->data[i]<<' ';
}
cout<<endl;
}
void Array::insert(int pos, int value)
{
for (int i = size; i > pos; i--)
data[i] = data[i - 1];
data[pos] = value;
size++;
}