
C++初学者, 帮忙解答下! 感激不尽!
#include<iostream>usingnamespacestd;classHuman{public:Human(){cout<<"基类构造"<<endl;}voi...
#include<iostream>
using namespace std;
class Human
{
public:
Human()
{
cout<<"基类构造"<<endl;
}
void stand()
{
cout<<"I can stand!"<<endl;
}
void run()
{
cout<<"I can run"<<endl;
}
~Human()
{
cout<<"基类析构"<<endl;
}
};
class Father :public Human
{
public:
Father()
{
cout<<"子类构造"<<endl;
}
void run()
{
cout<<"I run faster!"<<endl;
}
void eat()
{
cout<<"I can eat"<<endl;
}
~Father()
{
cout<<"子类析构"<<endl;
}
};
int main(void)
{
Human *p=new Father;
delete p;
return 0;
}
谁能帮忙解释下 为什么执行了基类的构造函数和派生类的构造函数,但是只执行了基类的析构函数, 而没有执行派生类的析构函数。 展开
using namespace std;
class Human
{
public:
Human()
{
cout<<"基类构造"<<endl;
}
void stand()
{
cout<<"I can stand!"<<endl;
}
void run()
{
cout<<"I can run"<<endl;
}
~Human()
{
cout<<"基类析构"<<endl;
}
};
class Father :public Human
{
public:
Father()
{
cout<<"子类构造"<<endl;
}
void run()
{
cout<<"I run faster!"<<endl;
}
void eat()
{
cout<<"I can eat"<<endl;
}
~Father()
{
cout<<"子类析构"<<endl;
}
};
int main(void)
{
Human *p=new Father;
delete p;
return 0;
}
谁能帮忙解释下 为什么执行了基类的构造函数和派生类的构造函数,但是只执行了基类的析构函数, 而没有执行派生类的析构函数。 展开
2个回答
展开全部
你把Human改成Father
Father *p=new Father;
\
你上面的p是基类指针,
当然只有基类析构函数被调用
Father *p=new Father;
\
你上面的p是基类指针,
当然只有基类析构函数被调用
更多追问追答
追问
首先谢谢你,
那可不可以这样解释
系统先执行new Father
先调基类的构造,再调派生类的构造
然后把地址给了基类指针P
P只能调基类的析构。
追答
是的,
new Father这个没问题,先构造基类,在构造子类.
delete p;因p是基类指针,所以在释放的时候,只调基类.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询