1.
-
//基数student的析构函数不是vi
-
#include <iostream>
-
#include <stdio.h>
-
using namespace std;
-
-
class student{
-
public:
-
student(){
-
printf("%s constructor\n", __FUNCTION__);
-
}
-
~student(){
-
printf("%s destructor\n", __FUNCTION__);
-
}
-
//virtual void study();
-
private:
-
string m_name;
-
};
-
-
class studentLeader:public student{
-
public:
-
studentLeader() {
-
printf("%s constructor\n", __FUNCTION__);
-
}
-
~studentLeader(){
-
printf("%s destructor\n", __FUNCTION__);
-
}
-
//virtual void study();
-
};
-
-
-
-
int main(int argc, char **argv)
-
{
-
studentLeader *sl = new studentLeader();
-
delete sl;
-
return 0;
-
}
-
-
./a.out
-
student constructor
-
studentLeader constructor
-
~studentLeader destructor
-
~student destructor
出现问题了。
student的析构函数不是virtual,编译器对其使用静态联编,根据指针类型(student*),只调用student的析构函数
-
int main(int argc, char **argv)
-
{
-
student *s = new studentLeader();
-
delete s;
-
return 0;
-
}
-
-
./a.out
-
student constructor
-
studentLeader constructor
-
-
~student destructor
2. 基数的析构函数使用virtual
原则:析构函数应当是虚函数,除非类不用作基数。
-
-
#include <iostream>
-
#include <stdio.h>
-
using namespace std;
-
-
class student{
-
public:
-
student(){
-
printf("%s constructor\n", __FUNCTION__);
-
}
-
virtual ~student(){
-
printf("%s destructor\n", __FUNCTION__);
-
}
-
//virtual void study();
-
private:
-
string m_name;
-
};
-
-
class studentLeader:public student{
-
public:
-
studentLeader() {
-
printf("%s constructor\n", __FUNCTION__);
-
}
-
~studentLeader(){
-
printf("%s destructor\n", __FUNCTION__);
-
}
-
//virtual void study();
-
};
-
-
int main(int argc, char **argv)
-
{
-
//指针类型是基数
-
student *s = new studentLeader();
-
delete s;
-
return 0;
-
}
-
./a.out
-
student constructor
-
studentLeader constructor
-
~studentLeader destructor //关键
-
~student destructor
阅读(806) | 评论(0) | 转发(0) |