1.请写出下面这个类的方法代码
class String
{
public:
String(char *pstr)
{
if(pstr!=NULL)
{
_pstr = new char[strlen(pstr)+1];
strcpy(_pstr,pstr);
}
else
{
_pstr = new char[1];
*_pstr='\0';
}
}
~String()
{
delete [] _pstr;
_pstr = NULL:
}
String(const String &src)
{
_pstr = new char[strlen(src._pstr)+1];
strcpy(_pstr,src._pstr);
}
void operator=(const String &src)
{
if(&src == this)
{
return;
}
delete [] _pstr;
_pstr = new char[strlen(src._pstr)+1];
strcpy(_pstr,src._pstr);
return;
}
private:
char *_pstr;
};
2.请完成下面这个类的方法代码,请实现带头节点的单链表。
class Link
{
public:
Link()//构造函数
{
_phead=new Node();
}
~Link() //析构函数
{
while(_phead->_pnex!=NULL)
{
Node *tmp = _phead->_pnext;
_phead->_pnext=tmp->_pnext;
delete tmp;
tmp = NULL;
}
delete _phead;
_phead = NULL;
}
void insertHead(int val) //头插法
{
Node *tmp =new Node(val);
tmp->_pnext = _phead->_pnext;
_phead->_pnext = tmp;
}
void insertTail(int val) //尾插法
{
Node *p = _phead;
Node *ins = new Node(val);
while(p->_pnext!=NULL)
{
p = p->_pnext;
}
p->_pnext = ins;
}
void deleteNode(int val)//删除链表所有值为val的节点
{
Node *pre = _phead;
Node *p =_phead->_pnext;
while(p!=NULL)
{
if(p->data=val);
{
Node *tmp = p;
p=p->_pnext;
pre->_pnext = tmp->_pnext;
delete tmp;
tmp = NULL;
}
else
{
pre=pre->_pnext;
p=p->_pnext;
}
}
}
private:
class Node
{
public:
Node(int data=0):_data(data), _pnext(NULL){}
int _data;
Node *_pnext;
};
Node *_phead;
};
3.请给出下面对象创建过程中涉及的打印。
class Test
{
public:
Test(int a=5, int b=5):ma(a), mb(b)
{cout<<"Test(int, int)"<<endl;}
~Test()
{cout<<"~Test()"<<endl;}
Test(const Test &src):ma(src.ma), mb(src.mb)
{cout<<"Test(const Test&)"<<endl;}
void operator=(const Test &src)
{ma = src.ma; mb = src.mb; cout<<"operator="<<endl;}
private:
int ma;
int mb;
};
Test t1(10, 10);
int main()
{
Test t2(20, 20);
Test t3=t2;
static Test t4 = Test(30, 30);//构造t4
t2 = Test(40, 40);//构造临时对象 赋值 析构临时对象
t2 = (Test)(50, 50);//构造临时对象 赋值 析构临时对象
t2 = 60;;//构造临时对象 赋值 析构临时对象
Test *p1 = new Test(70, 70);
Test *p2 = new Test[2];
Test *p3 = &Test(80, 80);//构造 析构
Test &p4 = Test(90, 90);//构造
delete p1;
delete []p2;
}
Test t5(100, 100);
4.