虚函数 与 纯虚函数

#include <iostream>
using namespace std;

class Base
{
    public:
      
 /* virtual */ ~Base() { cout << "Base::~Base" << endl; }
        Base() { cout << "Base::Base" << endl; }
};

class Third : public Base
{
    public:
        ~Third() { cout << "Third::~Third" << endl; }
        Third() { cout << "Third::Third" << endl; }
};
int main(int argc, char **argv)
{
    cout << "Constructure Third:" << endl;
    Base *t = new Third;
    cout << "Constructure Third:" << endl;
    Third *q = new Third;
    cout << "Deconstructure Third:" << endl;
    delete q;
    cout << "Deconstructure Third:" << endl;
    delete t;
    return 0;
}
[flydream@flydream C++]$

[flydream@flydream C++]$ ./a.out
Constructure Third:
Base::Base
Third::Third
Constructure Third:
Base::Base
Third::Third
Deconstructure Third:
Third::~Third
Base::~Base
Deconstructure Third:
Base::~Base

如果在基类的析构函数中加上VIrtual则结果为

[flydream@flydream C++]$ ./a.out
Constructure Third:
Base::Base
Third::Third
Constructure Third:
Base::Base
Third::Third
Deconstructure Third:
Third::~Third
Base::~Base
Deconstructure Third:
Third::~Third
Base::~Base

C++中的虚函数和纯虚函数用法

  1.虚函数和纯虚函数可以定义在同一个类(class)中,含有纯虚函数的类被称为抽象类(abstractclass),而只含有虚函数的类(class)不能被称为抽象类(abstractclass)。

  2.虚函数可以被直接使用,也可以被子类(subclass)重载以后以多态的形式调用,而纯虚函数必须在子类(subclass)中实现该函数才可以使用,因为纯虚函数在基类(baseclass)
只有声明而没有定义。

  3.虚函数和纯虚函数都可以在子类(subclass)中被重载,以多态的形式被调用。

  4.虚函数和纯虚函数通常存在于抽象基类(abstractbase class-ABC)之中,被继承的子类重载,目的是提供一个统一的接口。

  5.虚函数的定义形式:virtual {method body};纯虚函数的定义形式:virtual { } = 0;在虚函数和纯虚函数的定义中不能有static标识符,原因很简单,被static修饰的函数在编译时候要求前期bind,然而虚函数却是动态绑定(run-timebind),而且被两者修饰的函数生命周期(life recycle)也不一样。

   6.如果一个类中含有纯虚函数,那么任何试图对该类进行实例化的语句都将导致错误的产生,因为抽象基类(ABC)是不能被直接调用的。必须被子类继承重载以后,根据要求调用其子类的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值