虚函数

时间:2010-05-28 05:40:23

标签: java c++

什么是虚拟功能?什么是纯虚函数?请用例子说明

2 个答案:

答案 0 :(得分:7)

wikipedia有一个很好的解释。

虚拟函数和纯虚函数之间的

Difference虚函数具有实现,您可以选择覆盖它。 纯虚函数(Java中的抽象)没有实现,您必须在子类中实现它(除非您的子类也是抽象的)。

答案 1 :(得分:3)

/**
Virtual Function : A virtual function is a member function that is declared
within a base class and redefined by a derived class.

A base class pointer can be used to point an object of any class derived from
that base. When a base pointer points to a derived object that contains a 
virtual function, C++ determines which version of that function to call based
upon the type of object pointed by the pointer.

*/

#include < iostream >
using namespace std;

class baseclass 
{
    public :
    virtual void vfunc() { cout << "This is base class vfunc\n"; };
};

class derived : public baseclass {
    public :
    void vfunc() { cout << "This is derived class vfunc\n"; };
};

class derived2 : public baseclass {};

int main () 
{
    class baseclass * ptr, b;   // baseclass pointer and its object
    class derived d;        // object of derived class
    class derived2 d2;      // object of derived2 class
    ptr = &b;           // ptr points to baseclass
    ptr->vfunc();       // vfunc of base class will execute
    ptr = &d;           // ptr points to derived class
    ptr->vfunc();       // vfunc of derived class will execute
    ptr = &d2;      // ptr points to derived2 class
    ptr->vfunc();       // vfunc of base class will execute
    return 0;
}    

******************************************************************************

/*
In a Pure Virtual Function, base class have no definition of virtual function
*/

#include < iostream >
using namespace std;

class baseclass 
{
    public :
    virtual void vfunc() = 0 ;  // Pure virtual function
};

class derived : public baseclass {
    public :
    void vfunc() { cout << "This is derived class vfunc\n"; };
};

class derived2 : public baseclass {
    public :
    void vfunc() { cout << "This is derived2 class vfunc\n"; };
};

int main () 
{
    class derived d;        // object of derived class
    class derived2 d2;      // object of derived2 class
    d.vfunc();      // vfunc of derived class will execute
    d2.vfunc();     // vfunc of derived2 class will execute
    return 0;
}