#include <iostream>
using namespace std;
class N //抽象基类
{
public:
N() : m(0) {}
virtual ~N() {}
public:
virtual void f() const = 0; //纯虚函数
protected:
int m;
};
class A : public N
{
public:
A() :x(0) {}
virtual ~A() {}
public:
virtual void f() const ; //定义纯虚函数
protected:
int x;
};
void A::f() const
{
cout<<m<<endl<<x<<endl;
}
class B : public A
{
public:
B() : y(0) {}
virtual ~B() {}
public:
virtual void f() const ; //再次定义纯虚函数
protected:
int y;
};
void B::f() const
{
cout<<m<<endl<<x<<endl<<y<<endl;
}
int main ()
{
N *p = NULL;
B ob1;
p = &ob1;
p->f();
}
我对虚函数的浅显理解:
1、析构函数不管三七二十一全加virtual ,使其成为虚函数;
2、只要有一个纯虚函数的类就是抽象基类了,就不能用它定义对象了;但是可以有构造函数、析构函数。
3、用最顶层的含有虚函数的类定义一个指针,就可以用这个指针指向不同的派生类的对象,从而调用该派生类的虚函数