题目:
给出的头文件:
#include <iostream>
#include "array.h"
using namespace std;int main()
{Array a1;int n;cin >> n;for (int i = 0;i != n; ++i) {int t;cin >> t;a1.Push_back(t);}Array a2(a1);cout << "\nThere're " << a2.length() << " numbers:" << endl;a2.Print();a2.Push_back(10);cout << "\nAfter push_back,";cout << "there're " << a2.length() << " numbers:" << endl;a2.Print();Array a3;a3.Print();a3 = a1;cout << "After operator=,";cout << "there're " << a3.length() << " numbers:" << endl;a3.Print();
}
考点:
动态空间分配
法一:new
array.h
/**********Program**********/class Array
{private:int size;int *ptr;public:Array();Array(const Array& a);~Array();void Push_back(int v);Array& operator=(const Array& a);int length();void Print();
};/********** End **********/
array.cpp
/**********Program**********/
#include"array.h"
#include <iostream>
using namespace std;Array::Array(const Array& a)
{if(a.size>0){size=a.size;ptr=new int[size];for(int i=0;i<size;i++)ptr[i]=a.ptr[i];}
}
Array::Array()
{size=0;ptr=new int[size];//可以理解为构建数组ptr[size]
}Array::~Array(){delete []ptr;ptr=NULL;
}Array& Array::operator=(const Array& a)
{delete []ptr;if(a.size>0){size=a.size;ptr=new int[size];for(int i=0;i<size;i++){ptr[i]=a.ptr[i];}}else ptr=NULL;
}void Array::Print()
{if(size!=0){for(int i=0;i<size;i++){cout<<ptr[i];if(i!=size-1)cout<<" ";}cout<<"\n";}elsecout<<"\nIt's empty!\n";
}
void Array::Push_back(int v)
{int *temp=new int[size+1];for(int i=0;i<size;i++)temp[i]=ptr[i];temp[size]=v;delete []ptr;ptr=temp;size++;
}
int Array::length()
{return size;
}/********** End **********/