能不能帮忙写一下c++类的构造函数,拷贝构造函数,赋值运算符=号的操作符重载,析构函数?求教!

2025-06-28 22:27:24
推荐回答(1个)
回答1:

class Test
{
private:
char * data;
unsigned int len; //记录data 长度
public:
Test(void);
Test(Test &item);
Test::Test(char * item,int n);
void operator =(Test& item);

~Test(void);
};


Test::Test(void)
{
this->data = 0; // 这里一般使用null 代替0
this->len = 0;
}

Test::Test(Test& item) //拷贝
{
unsigned int itemLen = item.len;
char *p,*q;
this->len = item.len;
if( this->len == 0 ) //如果长度为0 初始化数据
{
this->data = 0;
return;  
}

this->data = new char[itemLen];
p = this->data;
q = item.data;
while( itemLen-- &&(*p++ = *q++));

return;  
}

void Test::operator=(Test& item)
{
unsigned int itemLen = item.len;
char *p,*q;
if( this->len > 0)
{
this->len = 0;
delete[] data;
}

this->len = item.len;
if( this->len == 0 )
{
this->data = 0;
return;  
}

this->data = new char[itemLen];
p = this->data;
q = item.data;
while( itemLen-- &&(*p++ = *q++));

return;

}

Test::~Test()
{
if( this->len > 0)
{
delete[] data;
}
}

Test::Test(char * item,int n)
{
unsigned int len = n;
 char *p,*q;
this->len = n;
if( this->len == 0 )
{
this->data = 0;
return;  
}

this->data = new char[n];
p = this->data;
q = item;
while( len-- &&(*p++ = *q++));

return;
 

}