C++多态基础(polymorphism)

来源:互联网 发布:华彩软件下载站 编辑:程序博客网 时间:2024/06/15 08:14

记录自己学习c++多态的一些知识点笔记,不全,但是是自己本来并不熟悉的一些地方,简单的地方省略。。。

多态,“一个接口,多种方法”。

1、多态的两种类型
(1)编译时多态
a、函数重载
b、运算符重载

(2)运行时多态
association done during run time.Implemented by dynamic biding.(inheritance + virtual function)
即,通过动态绑定来实现
使用基类指针或者基类引用来访问虚函数来实现的

2、static biding
Done during complie time
Applied to non-vurtual function

It is the compile-time determination of which function to call for a particular object based on the type of the formal parameter.

When pass-by-value is used, static biding occurs.

3、dynamic biding
Done during run time
Applied to virtual function

It is the run-time determination of which function to call for a particular object of a descendant class based on the type of the arguement.

Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic biding.

4、virtual function与继承相结合以实现运行时的多态性。在公有继承层次中的一个或多个派生类中对虚函数进行重定义(基类的也可以定义),然后通过指向基类的指针(或引用)调用虚函数来实现运行时的多态性。

5、
eg:

void Fun(class_A & param) {    param.memberfun();}

若memberfun非虚,则由形参类型决定调用(静)
若memberfun为虚,则由实参类型决定调用(动)

6、动态绑定的另一实现方式:使用引用形参,通过基类引用调用虚函数

7、关于虚函数
虚函数是在基类中被声明virtual,并在派生类中重新定义的成员函数,可实现成员函数的动态覆盖。
直接在基类中的virtual是会在虚函数中调用子类函数,而这个子类函数在各个派生类中都是具有的

a在派生类中重定义从基类中继承过来的虚(函数原形不变)该重定义的函数在该派生类中仍是虚。(但是在派生类中不用加virtual了)
b函数重载,虚特性丢失
c若派生类没有重新定义虚函数,则使用基类定义的虚函数的版本

8、抽象类:有纯虚函数的类称为抽象类
ps:
1只能用作基类
2不能声明实例
3不能用于传参合返回值类型
4不能用于显示转换
5可以声明关于它的指针和引用
6纯虚函数在基类中没有定义,但要求在任何派生类都要定义自己的实现方法(如果不是纯虚的话,派生类可以不用实现,沿用基类的就好)
7抽象类中的纯虚函数,在派生类的声明中也要加上virtual的定义


写得略微有点凌乱,可能是一种强化版的笔记吧,零基础的同学可能看完了还是不太清楚。。。=_=
备注,学习就好

0 0
原创粉丝点击