zoukankan      html  css  js  c++  java
  • 【c++题目003】关于析构

    Which statement is false?

    a) Destructors are called when a pointer is deleted.

    b) Destructors are called when an object goes out of scope.

    c) Destructors are called when a reference goes out of scope.

    d) A virtual destructor should be used if the class has virtual methods.

    e) Base class destructors are called after derived class destructors.

    /*
    关于析构
    Which statement is false?
    a) Destructors are called when a pointer is deleted.
    b) Destructors are called when an object goes out of scope.
    c) Destructors are called when a reference goes out of scope.
    d) A virtual destructor should be used if the class has virtual methods.
    e) Base class destructors are called after derived class destructors
    */
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <assert.h>
    using namespace std;
    
    class Parent
    {
    public:
    	virtual ~Parent()
    	{
    		cout << "~Parent" << endl;
    	}
    	virtual void func(){
    		cout << "Parent->func"<<endl;
    	}
    };
    class Son:public Parent
    {
    public:
    	virtual ~Son()
    	{
    		cout << "~Son" << endl;
    	}
    	virtual void func(){
    		cout << "Son->func" << endl;
    	}
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	//Parent * pParent = new Parent;
    	//{
    	//	Parent p; //超出作用域也要调用析构函数
    	//}
    	//cout << "delete pParent..." << endl;
    	//delete pParent; // delete对象指针时会调用析构函数
    
    	////////////////////////////////////////////////////////////////////////////
    	//Parent p;
    	//{
    	//	Parent& rP = p; //引用超出作用域时,是不会析构对象的,只是“引用而已”
    	//}
    
    
    	
    	//当通过子类指针析构子类对象 或者 子类对象超过作用域时
    	//不管析构函数是否是虚函数,都是先执行子类的析构函数,
    	//再调用父类的析构函数,这跟构造时的顺序相反
    	//Son s; 
    	//Son * s = new Son;
    	//delete s;
    
    
    	//当通过父类指针析构子类对象时,如果
    	//析构函数是虚函数,则delete时,根据子类对象的虚函数表,查到要调用的
    	//析构韩式是子类的版本,这时调用子类的析构函数,然后析构父类,才调用父类
    	//的析构函数
    	//但当析构函数不是虚函数时,将直接调用父类的析构函数,而不会调用子类的析构函数,会造成资源泄漏
    //所以一般有继承关系的类,都要将析构函数定义为虚函数 Parent * s = new Son; //s->func(); delete s; }

    另外,对于virtual这个关键词,一般在父类中的方法定义了之后,子类不需再写virtual也是虚函数,但为了清楚起见,凡是虚函数都最好写上virtual

  • 相关阅读:
    prometheus 基于文件的目标发现
    prometheus rules
    consul kv使用介绍
    prometheus 标签使用
    prometheus 配置容器 cadvisor监控节点
    prometheus 配置介绍
    Ubuntu 13.10 录音有特别大噪音解决办法
    Ubuntu 13.10 解决虚拟机摄像头无法使用问题
    Ubuntu 13.10 安装软件失败后出现的问题——已安装 post-installation 脚本 返回了错误号 1
    Ubuntu 13.04 VirtualBox在工作区中的切换
  • 原文地址:https://www.cnblogs.com/speedmancs/p/2072713.html
Copyright © 2011-2022 走看看