今日总结11_10

1.c++虚函数问题。巩固:如果一个基类的指针指向一个派生类的对象,想delete掉该对象,不会执行派生类的dstructer,只会执行基类的;将派生类的析构函数生命为virtual之后,会先执行派生类的然后执行基类的;并且,方便的是,将基类析构函数声明为虚的,派生类也自动变为虚的。

#include <iostream>

using namespace std;

class Base
{
public:
    ~Base(){cout << "Destructing Base!" << endl;}
};

class Derive : public Base
{
public:
    virtual ~Derive(){cout << "Destructing Derive! "<< endl;}
};
int main(void)
{
 Derive d;
 Base b;
  
 return 0;
输出结果为:Destructing Base!  Destructing Derive!  Destructing Base!

或者main()中的构造顺序改为Base b;Derive d;输出为:Destructing Derive!  Destructing Base!Destructing Base!

加这一点,主要是为了说明情况。

另外,基类名*  指针 = new 子类名(); 只有当一个父类类型的指针 指向 子类对象[new 的对象]时 ,只有将 基类的析构函数 声明为 虚函数virtual, 在 delete 指针才会:先执行派生类对象的析构函数 ,然后再执行基类的析构函数.否则:只执行基类的析构函数.

(原帖中,new derive();语句,derive后加了括号,说明一下,加括号调用没有参数的构造函数,不加括号调用默认构造函数)

原帖链接为:http://www.ituring.com.cn/article/details/16628 (by 陈利人)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值