帶有指針型數據成員的類新手初學C++心得
作者: 來源: 發布時間:2011-3-15 16:50:37 點擊:
最近打算寫一個算法類,算法類中要有一個指針型數據成員,然而該指針型數據成員卻不能在構造函數只能夠分配堆內存(因為此時我們還不確定數組的維度),只有調用了某個函數之后,方知道動態數組維度,考慮不在類的構造函數中調用確定數組維度的那個函數做如下設想:
在類的其他其他成員函數中為該指針成員分配堆內存,析構函數中釋放該數據成員。問了幾個同學和網友后做如下設計:
![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
class stringprocess
{
public:
stringprocess(void);
~stringprocess(void);
//int GetLongestCommonSequence(wstring x,wstring y,wstring result);
void test();
private:
int *indexes;//聲明指向指針的指針,保存兩個字符串中的最長公共序列中的字符分別出現的位置。
wstring xpart;//最大公共字序列的父串之一
wstring ypart;//
};![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
該類的構造函數
{
public:
stringprocess(void);
~stringprocess(void);
//int GetLongestCommonSequence(wstring x,wstring y,wstring result);
void test();
private:
int *indexes;//聲明指向指針的指針,保存兩個字符串中的最長公共序列中的字符分別出現的位置。
wstring xpart;//最大公共字序列的父串之一
wstring ypart;//
};
![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
stringprocess::stringprocess(void)
{
indexes=NULL;
}
{
indexes=NULL;
}
該類的析構函數
:
stringprocess::~stringprocess(void)
{
if (indexes!=NULL)
{
cout<<"指針成員變量已經被分配了堆內存,需要以delete模式釋放"<<endl;
delete[] indexes;
cout<<"釋放完畢"<<endl;
}
else
{
cout<<"指針成員變量為被分配堆內存,不需要以delete模式釋放"<<endl;
}
cout<<"destructor"<<endl;
}
{
if (indexes!=NULL)
{
cout<<"指針成員變量已經被分配了堆內存,需要以delete模式釋放"<<endl;
delete[] indexes;
cout<<"釋放完畢"<<endl;
}
else
{
cout<<"指針成員變量為被分配堆內存,不需要以delete模式釋放"<<endl;
}
cout<<"destructor"<<endl;
}
上一篇:C#代碼反編譯 得到項目可運行源碼 經驗分享 下一篇:
[收藏此文章]