回 帖 发 新 帖 刷新版面

主题:一个关于继承的小程序的异常结束

编写了一个关于类继承的简单的程序,没报错,但是运行没结果,vc提示出现异常.请帮忙看看. 
#include<iostream.h>
#include<string.h>
  
class sample{
    private:
            int x; 
            char *name;
    public:
        sample(){
       x=0; name=0;
        }
        sample(int a,char *p){
          x=a;
          if(name)delete name;
           name=new char[sizeof(p)+1];
          {
            strcpy(name,p);
            name[sizeof(p)]=0;
           }
          // delete p;
        }
    void setx(int a){
          x=a;
        }
    int    getx(){
          return x;
        }
    void setname(char *p){
          if(name) delete name;
          name=new char [sizeof(p)+1];
          if(name){
           strcpy(name,p);
            delete p;
          }
        }
    char *getname(){
           if(name) return name;
   
        }
    ~sample(){
            cout<<"~sample!"<<endl;
        if(name) delete name;
    }

};
class samplenext: public sample{
                      int y;          
                      
               public:      
                      samplenext():sample(){
                       y=0;
                      }
                      samplenext(int a,int b,char *name):sample(b,name){
                           y=a;
                         }
                      void sety(int a){
                        y=a;
                      }
                      int gety(){
                       return y;
                      }

};
void main()
{
  samplenext a1;
  samplenext a2(4,5,"hello!");
  a1.setx(1);a1.sety(1);
  cout<<"a1.x="<<a1.getx()<<endl;
  cout<<"a1.y="<<a1.gety()<<endl;
  cout<<a2.getname()<<endl;
}

回复列表 (共1个回复)

沙发


sample(int a,char *p){
          x=a;
          if(name)delete name;
           name=new char[sizeof(p)+1];
          {
            strcpy(name,p);
            name[sizeof(p)]=0;
           }
这个里面出错了,第二个对象a2一构造进入该构造函数,实际上name并没有分配空间,但编译器给了他个随机值,所以执行delete命令,去释放并没有分配的内存空间,所以出错。
其次在sample的析构函数里面 出错,我还没有找到原因。

我来回复

您尚未登录,请登录后再回复。点此登录或注册