c++ - 构造函数中的类错误

标签 c++ class dynamic constructor

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”给我运行时错误!!

错误:

Unhandled exception at 0x651157aa (msvcr100d.dll) in test0.exe: 0xC0000005: Access violation reading location 0xccccccc0.

最佳答案

这里:

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

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

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

关于c++ - 构造函数中的类错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18432403/

相关文章:

python - 二进制搜索和外部函数 'return'错误

java - 如何将 "dynamically"对象类型的实例转换为其特定数据类型?

java - 使用引用编译动态加载的类

c++ - 如何根据常量和返回类型调用重载函数?

c++ - 返回迭代器似乎使它无效

c++ - 计算目录中具有给定扩展名的文件数 - C++?

java - 在JAVA中向列表中的每个对象添加完整的对象列表

java - 如何从正在运行的应用程序的堆转储中提取 Java 类定义?

c++ - 将 map 值保留为 vector

C# - 动态参数是否装箱