拷贝构造函数格式为
classname (const classname &object)
{
//do something
}
下面的程序可以说明问题,为什么拷贝构造函数是必要的
class samp
{
char * s;
int num;
public:
samp(int i)
{
s='/0';
num = i;
cout << num << endl;
}
//拷贝构造函数
samp(samp& obl)
{
int l = strlen(obl.s);
s = new char[l + 1];
strcpy(s, obl.s);
}
samp()
{
}
~samp()
{
if (s)
delete[] s;
cout << "Freeing s[" << num << "]" << endl;
}
void show()
{
cout << s << "/n";
}
void set(char * str);
};
void samp::set(char * str)
{
s = new char[strlen(str) + 1];
if (!s)
{
cout << " allocation error./n";
exit(1);
}
strcpy(s, str);
}
void main(void)
{
samp ob;
ob = input();
ob.show();
return 0;
}