zoukankan      html  css  js  c++  java
  • c++使用技巧: 不要在构造函数/析构函数中调用虚函数

    构造函数中调用虚函数将会因为派生类没有完成自身的初始化,而使得只能调用基类的虚函数定义,如果基类没有给出虚函数的实现,则会编译出错时出错(LNK2019没有找到对应函数的实现)。


    析构函数中调用虚函数(同时需要保证基类析构函数是虚函数,否则删除基类指针将不会调用派生类得析构函数)。

    测试代码:

    class Base
    {
    public:
    	Base()
    	{
    		cout<<"Base::Base"<<endl;
    		Fun();
    	}
    	virtual ~Base()
    	{
    		cout<<"Base::~Base"<<endl;
    		Fun1();
    	}
    private:
    	virtual void Fun() = 0;
    	virtual void Fun1();
    };
    void Base::Fun()
    {
    	cout<<"Base::Fun"<<endl;
    }
    void Base::Fun1()
    {
    	cout<<"Base::Fun1"<<endl;
    }
    class Derived : public Base
    {
    public:
    	Derived()
    	{
    		cout<<"Derived::Derived"<<endl;
    		Fun();
    	}
    	~Derived()
    	{
    		cout<<"Derived::~`Derived"<<endl;
    		//Fun1();
    	}
    private:
    	virtual void Fun();
    	virtual void Fun1();
    };
    void Derived::Fun()
    {
    	cout<<"Derived::Fun"<<endl;
    }
    void Derived::Fun1()
    {
    	cout<<"Derived::Fun1"<<endl;
    }
    如果基类以及派生类各自拥有不同的申请资源建议使用同名的函数放在析构函数中,不建议使用虚函数声明,否则将会有种假象,不过注意小心重复删除(保证各自释放资源是针对自身分配,或者统一由派生类来申请基类以及自身的资源。)。

  • 相关阅读:
    Python 三级菜单
    linux 下按文件类型删除
    linux 做内网端口映射
    ss
    fio
    libXtst.so.6 is needed by teamviewer-12.0.76279-0.i686
    copy 浅复制 与深复制
    Git 使用方法
    关于 爬虫使用 urllib.urlopen 提交默认 User-Agent值
    Python 官方模块文档
  • 原文地址:https://www.cnblogs.com/rogerroddick/p/2846707.html
Copyright © 2011-2022 走看看