MyArr.h
#pragma once
#include <iostream>
using namespace std;
class MyArray
{
public :
MyArray ( ) ;
explicit MyArray ( int capacity) ;
MyArray ( const MyArray& array) ;
void SetDate ( int pos, int val) ;
int GetData ( int pos) ;
void PushBack ( int val) ;
int GetLength ( ) ;
~ MyArray ( ) ;
private :
int mCapacity;
int nSize;
int * pAddress;
} ;
MyArr.cpp
#include "MyArr.h"
MyArray:: MyArray ( )
{
cout << "默认构造函数的调用" << endl;
this - > mCapacity = 0 ;
this - > nSize = 0 ;
pAddress = new int [ mCapacity] ;
}
MyArray:: MyArray ( int capacity)
{
cout << "有参构造函数的调用" << endl;
this - > mCapacity = capacity;
pAddress = new int [ mCapacity] ;
nSize = 0 ;
pAddress[ capacity] = { 0 } ;
}
MyArray:: MyArray ( const MyArray& array)
{
cout << "拷贝构造函数的调用" << endl;
pAddress = new int [ array. mCapacity] ;
this - > mCapacity = array. mCapacity;
for ( int i = 0 ; i < array. mCapacity; ++ i)
{
this - > pAddress[ i] = array. pAddress[ i] ;
}
}
void MyArray:: SetDate ( int pos, int val)
{
if ( pos< 0 || pos> mCapacity - 1 )
{
return ;
}
for ( int i = pos; i < mCapacity - 1 ; ++ i)
{
this - > pAddress[ i + 1 ] = pAddress[ i] ;
}
this - > pAddress[ pos] = val;
this - > nSize++ ;
}
int MyArray:: GetData ( int pos)
{
if ( pos< 0 || pos> mCapacity - 1 )
{
return - 1 ;
}
return this - > pAddress[ pos] ;
}
void MyArray:: PushBack ( int val)
{
if ( nSize == mCapacity)
{
return ;
}
this - > pAddress[ nSize] = val;
this - > nSize++ ;
}
int MyArray:: GetLength ( )
{
return this - > nSize;
}
MyArray:: ~ MyArray ( )
{
cout << "析构函数的调用" << endl;
if ( pAddress != NULL )
{
delete [ ] pAddress;
}
pAddress = NULL ;
}
数组类的封装.cpp
#include "MyArr.h"
void test ( )
{
MyArray* p = new MyArray ( 30 ) ;
MyArray p2 ( * p) ;
for ( int i = 0 ; i < 10 ; ++ i)
{
p2. PushBack ( i) ;
}
for ( int i = 0 ; i < p2. GetLength ( ) ; ++ i)
{
cout << p2. GetData ( i) << endl;
}
}
int main ( )
{
test ( ) ;
system ( "pause" ) ;
return 0 ;
}