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) で未処理の例外: 0xC0000005: 場所 0xccccccc0 を読み取るアクセス違反。

4

1 に答える 1