64,670
社区成员
发帖
与我相关
我的任务
分享
// xi_gou.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
class test{
public:
test(){
};
virtual void fun()
{
printf("hello world1\n");
}
~test()
{
fun();
}
};
int main(int argc, char* argv[])
{
test *a=new test;
delete a;
return 0;
}
#include <iostream>
class Base
{
public:
virtual void fun()
{
std::cout << "Base fun\n";
}
virtual ~Base(){this ->fun();}
};
class Derived:public Base
{
public:
void fun()
{
std::cout << "Derived fun\n";
}
};
int main()
{
Base *ptr(new Derived);
// ptr->fun();
delete ptr;
return 0;
}
输出:Base fun
问题2: 对象的销毁应该分为两个阶段:1、释放对象持有的资源。2、释放对象本身所占有的内存。析构函数只负责第一个阶段。第二个阶段是由编译器(在栈上定义的对象)或者delete(在堆上定义的对象)来完成。所以对象在析构函数的哪个地方释放其所持有的资源是有程序作者决定的。