c++学习之虚函数 virtual function 笔记

关键字:  virtual

形式:  两种

--------------

1    纯虚函   数     virtual void funtion() = 0;

2    一般虚函数    virtual void funtion();

--------------

使用特点:

1  如果(父)类有纯虚函数存在,也就是  virtual void funtion() = 0; 存在, 该类的子类或者子孙类无条件的要实现这个虚函数。实现的时候,前面无需再加 virtual关键字。

2  如果父类是一般虚函数,子类可以不实现这个虚函数。形如 virtual void funtion();这样的,子类就非必须实现它。

3  根据前面第一点,如果一个类里面存在  virtual void funtion() = 0; 这样的纯虚函数,那么这个类是无法直接 实例化一个对象的。

---------------

使用场合:

1  纯虚函数 virtual void funtion() = 0; 为了在父类中给后面的子类提一个框架,一个接口,起提纲契领的作用,而真正怎么操作,怎么实现,让子类去完成。

2  一般虚函数  virtual void funtion();  为了父类通过指针,访问子类而用。

-------------

 1 #include <iostream>

 2 using namespace std;

 3 

 4 class People {

 5 public:

 6     void func(People * base) ;

 7     virtual void eat() { cout << "I/m eat....." << endl;};

 8     virtual void run() = 0;

 9 };

10 

11 class man:public People{

12     public:

13         void eat() {cout <<"eat fish...." << endl;}

14         virtual void run() = 0;

15 };

16 

17 class boy:public man{

18     public:

19         void eat() {cout <<"boy eat...."<< endl;}

20         virtual void run() ;

21 };

22 

23 void boy::run()

24 {

25 

26 }

27 

28 void People::func(People * base)

29 {

30     base -> eat();

31 }

32 

33 int main(void)

34 {

35     boy b;

36 //    man m;

37     

38 //    m.eat();

39 

40     b.eat();

41     return 0;

42 }

 

你可能感兴趣的:(function)