如何在c++类的定义中实现动态分配

来源:百度知道 编辑:UC知道 时间:2024/05/31 19:51:56
请教一个c++问题,是否可以在c++类的定义中,使用new语句实现数组的动态分配对一个私有成员进行,如果可以又是如何实现的?请不吝赐教!

template<typaneme T>
class Test
{
public:
Test() : _p(null){}
void mynew(int N)
{
_p = new T[N]();//这里若用maloc,但它不会进行默认构造
}
void mydel()
{
delete _p[];//那么这里free
_p = null;
}
~Test()
{
if (_p)
delete _p[];
}

private:
T *_p;
};

class A
{
public:
A(char *s)
{
szChar = new char[strlen(s)+1];
strcpy(szChar, s);
}
~A()
{
delete []szChar;
}
private:
char *szChar;
};

new - delete
maloc-free

配对使用

上面正解