intArray.h
#include<iostream>
using namespace std;
#ifndef _XXXX_
#define _XXXX_
class intArray
{
public:
intArray();
intArray(int);
inArray(const intArray &x);
~intArray();
bool Set(int i,int elem);
bool Get(int i);
int length()const;
void reset(int size);
intArray &operator=(const intArray &other);
intArray operator+(const intArray &other);
intArray operator-(const intArray &other);
friend istream &operator>>(istream &in,intArray &other);
friend ostream &operator<<(ostream &out,intArray &other);
private:
int *element;
int arraysize;
};
#endif
``
intArray.cpp
#include<iostream>
using namespace std;
#include"intArray.h"
intArray::intArray()
{}
intArray::intArray(int size)
{
arraysize=size;
element=new int[size];
}
intArray::intArray(const intArray &x)
{
arraysize=x.arraysize;
element=new int[arraysize];
for(int i=0;i<arraysize;i++)
element[i]=x.element[i];
}
intArray::~intArray()
{
if(element!=NULL)
delete element;
}
bool intArray::Set(int i,int elem)
{
if(i>0&&i<arraysize)
{
element[i]=elem;
return true;
}
else
return false;
}
bool intArray::Get(int i)
{
if(i>0&&i<arraysize)
{
cout<<element[i]<<' ';
return true;
}
else
return false;
}
int intArray::length()const
{
return arraysize;
}
void intArray::reset(int size)
{
if(element!=NULL)
delete element;
element=new int[size];
arraysize=size;
}
intArray intArray &operator=(const intArray &other)
{
if(element!=NULL)
delete element;
element=new int[other.arraysize];
for(int i=0;i<arraysize;i++)
element[i]=other.element[i];
return *this;
}
intArray intArray::operator +(const intArray &other)
{
intArray temp(other.arraysize);
for(int j=0;j<arraysize;j++)
temp.element[j]=element[j]+other.element[j];
return temp;
}
intArray intArray::operator -(const intArray &other)
{
intArray temp(other.arraysize);
for(int i=0;i<arraysize;i++)
temp.element[i]=element[i]-other.element[i];
return temp;
}
istream &operator>>(istream &in,intArray &other)
{
for(int i=0;i<other.arraysize;i++)
in>>other.element[i];
return in;
}
ostream &operator<<(ostream &out,intArray &other)
{
for(int j=0;j<other.arraysize;j++)
out<<other.element[j]<<' ';
return out;
}
main.cpp
#include
using namespace std;
#include"intArray.h"
void main()
{
intArray a(10);
cout<<"请输入a"<<endl;
cin>>a;
cout<<"a为:"<<a<<endl;
intArray b(a);
cout<<"b为:";
cout<<b<<endl;
cout<<"下标为奇数的元素为:";
for(int l=0;l<10;l++)
{
if(l%2!=0)
{
b.Get(l);
b.Set(l,(l+1)*2);
}
}
cout<<endl;
cout<<"b为:"<<b<<endl;
intArray c(5);
cout<<"输入c:"<<endl;
cin>>c;
cout<<"c为:"<<c<<endl;
c.reset(10);
c=a;
cout<<"c重置后为:"<<c<<endl;
intArray d(10);
intArray e(10);
d=b+c;
e=b-c;
cout<<"d为:"<<d<<endl;
cout<<"e为:"<<e<<endl;
}