C++ (建構函式、解構函式、動態申請空間)
阿新 • • 發佈:2019-01-05
#include<iostream>
#include<string.h>
using namespace std;
//整型陣列:
class IntArray//動態陣列
{
public:
IntArray();
IntArray(const int*,unsigned short);
~IntArray();
void list();
void free();//釋放
int at(int);//返回指定下標元素
void mod(int,int);
private://資料
int *buf;
unsigned short iLen;
};
//修改元素
void IntArray::mod(int index,int value)
{
this->buf[index]=value;
}
//定位指定下標元素
int IntArray::at(int index)
{
return this->buf[index];
}
//構造方法
IntArray::IntArray():iLen(0)
{
this->buf=NULL;
}
IntArray::IntArray(const int* pb,unsigned short iLen):iLen(iLen)
{
//申請空間
this->buf=new int[iLen];
memcpy(this->buf,pb,sizeof(int)*iLen);
/*int i=0;
for(i=0;i<iLen;i++)
this->buf[i]=pb[i];
*/
}
//解構函式
IntArray::~IntArray()
{
cout<<"此物件要被釋放啦!"<<endl;
if(NULL!=this->buf)
{
// delete []this->buf;
this ->buf=NULL;//防止指向非法指標
this->iLen=0;
}
}
//釋放
void IntArray::free()
{
if(NULL!=this->buf)
delete[] this->buf;
}
void IntArray::list()
{
int i=0;
for(i=0;i<this->iLen;i++)
cout<<this->buf[i]<<" ";
cout<<endl;
}
void fun()
{
int buf[10]={1,2,3,4,5,6};
//物件例項化
IntArray e;
IntArray e1(buf,6); //申請堆區
//IntArray e2=e; //深拷貝
//傳送訊息
e1.list();
//釋放
// delete []e1.buf;
// e1.free();
// e1.list();//指向野指標
// e1.~IntArray(); //可以手動傳送訊息
}
int main()
{
// fun();
int buf[10]={1,2,3,4,5,6};
cout<<buf[0]<<endl;
IntArray e1(buf,6); //IntArray(const int* ,int)
IntArray e2(e1); //拷貝建構函式 IntArray(IntArray&)
e1.list();
e2.list();
//修改e1第2個元素
e1.mod(1,100);//只修改了e1中第2個元素,沒有修改e2
e1.list();
e2.list();
return 0;
}