【问题标题】:classes error at constructor构造函数中的类错误
【发布时间】:2013-08-25 18:42:46
【问题描述】:
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。

【问题讨论】:

  • 使用std::string。顺便说一句,delete[] NULL; 是无操作的。

标签: c++ class dynamic constructor


【解决方案1】:

这里:

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

是坏事发生的地方。 s 尚未初始化,您正在将其与 NULL 进行比较。为什么您最初的印象是NULL?这是未定义的行为。放弃条件 - 这是构建对象的地方,所以就这样做 - 构建它。

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

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    相关资源
    最近更新 更多