本人在学习C++类的时候遇到这个问题,这段代码执行不了总是有错误怎么破~
#include<iostream>#include<cstring>
using namespace std;
class Name
{public:
Name(char*pn);
Name(const Name &obj);
~Name();
void setName(char *);
void showName();
protected:
char *pName;
long size;
};
Name::Name(char *pn)
{cout<<"Coustructing"<<pn<<endl;
pName=new char[strlen(pn)+1];
if(pName!=0) strcpy_s(pName,strlen(pn)+1,pn);
size=strlen(pn);
}
Name::Name(const Name &obj)
{cout<<"copying"<<obj.pName<<"into its own block\n";
pName=new char[strlen(obj.pName)+1];
if(pName!=0)
strcpy_s(pName,strlen(obj.pName)+1,obj.pName);
size=obj.size;
}
Name::~Name()
{cout<<"Destructing"<<pName<<endl;
pName[0]='\0';
delete []pName;
pName=NULL;
size=0;
}
void Name::setName(char *pn)
{delete []pName;
pName=new char[strlen(pn)+1];
if(pName!=0) strcpy_s(pName,strlen(pn)+1,pn);
size=strlen(pn);
}
void Name::showName()
{cout<<pName()<<endl;
}
int main()
{Name obj1("NoName");
Name obj2=obj1;
obj1.showName();
obj2.showName();
obj1.setName("sundondpo");
obj2.setName("DuFu");
obj1.showName();
obj2.showName();
}