主题:一个关于继承的小程序的异常结束
编写了一个关于类继承的简单的程序,没报错,但是运行没结果,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;
}
#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;
}