C++ 构造函数中的类错误 类名{ char*s; 内伦; 公众: name(){//Default constr。 s=零; len=0; } //************************************************** ~name(){//Destruct。 如果(s!=NULL){ 删除[]s; s=零; } } //************************************************* 名称(const char*s1);//const。 char*getName();//fcn获取名称 int getLen();//fcn获取长度 void setName(const char*s1);//fcn set name }; void name::setName(常量字符*s1){ 如果(s!=NULL){ 删除[]s; s=零; } len=strlen(s1)+1; s=新字符[len];//返回*** strcpy(s,s1); } 名称::名称(常量字符*s1){ 如果(s!=NULL){ 删除[]s; s=零; } len=strlen(s1)+1; s=新字符[len];//返回*** strcpy(s,s1); } char*name::getName(){ 返回s; } int name::getLen(){ 返回strlen(s)+1; } int main() { charc[20]; cout>C; 名称AAA(C); 名称BBB; BBB.setName(C); cout
此处: 是坏情况发生的地方。C++ 构造函数中的类错误 类名{ char*s; 内伦; 公众: name(){//Default constr。 s=零; len=0; } //************************************************** ~name(){//Destruct。 如果(s!=NULL){ 删除[]s; s=零; } } //************************************************* 名称(const char*s1);//const。 char*getName();//fcn获取名称 int getLen();//fcn获取长度 void setName(const char*s1);//fcn set name }; void name::setName(常量字符*s1){ 如果(s!=NULL){ 删除[]s; s=零; } len=strlen(s1)+1; s=新字符[len];//返回*** strcpy(s,s1); } 名称::名称(常量字符*s1){ 如果(s!=NULL){ 删除[]s; s=零; } len=strlen(s1)+1; s=新字符[len];//返回*** strcpy(s,s1); } char*name::getName(){ 返回s; } int name::getLen(){ 返回strlen(s)+1; } int main() { charc[20]; cout>C; 名称AAA(C); 名称BBB; BBB.setName(C); cout,c++,class,dynamic,constructor,C++,Class,Dynamic,Constructor,此处: 是坏情况发生的地方。s尚未初始化,您正在将其与NULL进行比较。为什么您会认为它最初是NULL呢?这是未定义的行为。只需放弃条件-这是构建对象的地方,所以只需这样做-构建它 强制C++建议-使用 STD::String .< /P>使用 STD::String 。顺便说一下, Dele[[0];是NO-OP。 class name { char *s; int len; public: name(){ // Default constr.
s
尚未初始化,您正在将其与NULL
进行比较。为什么您会认为它最初是NULL
呢?这是未定义的行为。只需放弃条件-这是构建对象的地方,所以只需这样做-构建它
<>强制C++建议-使用<代码> STD::String .< /P>使用<代码> STD::String 。顺便说一下,<代码> Dele[[0];是NO-OP。
class name {
char *s;
int len;
public:
name(){ // Default constr.
s=NULL;
len =0;
}
//**************************************************
~name(){ // Destruct.
if (s!=NULL){
delete [] s;
s=NULL;
}
}
//*************************************************
name(const char * s1); // Constr.
char* getName(); //fcn get name
int getLen() ; // fcn get lenght
void setName(const char * s1); // fcn set name
};
void name::setName(const char * s1){
if (s!=NULL){
delete [] s;
s=NULL;
}
len = strlen(s1)+1;
s=new char [len]; // back***
strcpy(s,s1);
}
name::name(const char * s1){
if (s!=NULL){
delete [] s;
s=NULL;
}
len = strlen(s1)+1;
s=new char [len]; // back***
strcpy(s,s1);
}
char* name::getName(){
return s ;
}
int name::getLen(){
return strlen(s)+1 ;
}
int main()
{
char C[20];
cout << "Please enter a name: ";
cin >> C;
name AAA(C);
name BBB;
BBB.setName(C);
cout << "\nThe length of A(" << AAA.getName();
cout << ") is: \a" << AAA.getLen() << endl << endl;
cout << "\nThe length of B(" << BBB.getName();
cout << ") is: \a" << BBB.getLen() << endl << endl;
system("pause");
return 0;
}
name::name(const char * s1){
if (s!=NULL){