C++ 在继承中虚函数、纯虚函数、普通函数,三者的区别

1.虚函数(impure virtual)

  C++的虚函数主要作用是“运行时多态”,父类中提供虚函数的实现,为子类提供默认的函数实现

  子类可以重写父类的虚函数实现子类的特殊化。

  如下就是一个父类中的虚函数:

class A
{
public:
    virtual void out2(string s)
    {
        cout<<"A(out2):"<<s<<endl;
    }
};

2.纯虚函数(pure virtual)

  C++中包含纯虚函数的类,被称为是“抽象类”。抽象类不能使用new出对象,只有实现了这个纯虚函数的子类才能new出对象。

  C++中的纯虚函数更像是“只提供申明,没有实现”,是对子类的约束,是“接口继承”。

  C++中的纯虚函数也是一种“运行时多态”。

  如下面的类包含纯虚函数,就是“抽象类”:

class A
{
public:
    virtual void out1(string s)=0;
    virtual void out2(string s)
    {
        cout<<"A(out2):"<<s<<endl;
    }
};

3.普通函数(no-virtual)

  普通函数是静态编译的,没有运行时多态,只会根据指针或引用的“字面值”类对象,调用自己的普通函数

  普通函数是父类为子类提供的“强制实现”。

  因此,在继承关系中,子类不应该重写父类的普通函数,因为函数的调用至于类对象的字面值有关。

4.程序综合实例

#include <iostream>
using namespace std;

class A
{
public:
    virtual void out1()=0;  ///由子类实现
    virtual ~A(){};
    virtual void out2() ///默认实现
    {
        cout<<"A(out2)"<<endl;
    }
    void out3() ///强制实现
    {
        cout<<"A(out3)"<<endl;
    }
};

class B:public A
{
public:
    virtual ~B(){};
    void out1()
    {
        cout<<"B(out1)"<<endl;
    }
    void out2()
    {
        cout<<"B(out2)"<<endl;
    }
    void out3()
    {
        cout<<"B(out3)"<<endl;
    }
};

int main()
{
    A *ab=new B;
    ab->out1();
    ab->out2();
    ab->out3();
    cout<<"************************"<<endl;
    B *bb=new B;
    bb->out1();
    bb->out2();
    bb->out3();

    delete ab;
    delete bb;
    return 0;
}

执行结果:

 

posted on 2014-02-27 09:18  旭东的博客  阅读(90259)  评论(6编辑  收藏  举报

导航