2013-08-25 120 views
2
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; 
} 

当我运行的代码,类“BBB”执行成功,但“AAA”给我的运行时错误!在构造函数的类错误

错误:test0.exe在0x651157aa(msvcr100d.dll)

未处理的异常:0000005:访问冲突读取位置0xccccccc0。

+1

使用'std :: string'。顺便说一下,'delete [] NULL;'是一个无操作。 – chris

回答

6

这里:

name::name(const char * s1){ 
    if (s!=NULL){ 

是当不好的事情发生。 s尚未初始化,您将其与NULL进行比较。你为什么最初的印象是NULL?这是未定义的行为。只是抛弃条件 - 这是对象构建的地方,所以做到这一点 - 构建它。

强制性C++建议 - 使用std::string