首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

运行时出现bug解决方案

2012-10-15 
运行时出现bugC/C++ code#include iostreamusing namespace stdclass Student{public:Student(char *pn

运行时出现bug

C/C++ code
#include <iostream>using namespace std;class Student{public:    Student(char *pname="no name"){        cout<<"create one student"<<endl;        name=new char(strlen(pname)+1);        strcpy(name,pname);        total++;        cout<<"学生人数: "<<total<<endl;    }    ~Student(){        cout<<"destruct one student"<<endl;        total--;        cout<<"学生人数: "<<total<<endl;        delete[]name;//感觉这里有运行时有bug,注释改行bug消失    }    static int number(){        return total;    }private:    char *name;    static int total;};int Student::total=0;void fn(){    Student stu1;    Student stu2;}int main(void){    fn();    cout<<Student::number()<<endl;    //cout<<Student::total<<endl;    return 0;}


[解决办法]
道理就是:new char(strlen(pname)+1);仅仅new了一个字符,用[]才是new一个数组。

热点排行