8.1多态性

第8章 虚函数与多态性

多态性是指一个名字,多种语义;或界面相同,多种实现。

重载函数是多态性的一种简单形式。

虚函数允许函数调用与函数体的联系在运行时才进行,称为动态联编。

8.1 静态联编

 

8.1 静态联编

联编是指一个程序模块、代码之间互相关联的过程。

静态联编,是程序的匹配、连接在编译阶段实现,也称为早期匹配。重载函数使用静态联编。

动态联编是指程序联编推迟到运行时进行,所以又称为晚期联编。

switch语句和if语句是动态联编的例子。

普通成员函数重载可表达为两种形式:

1.在一个类说明中重载

例如:Show(int,char);

Show(char *,float);

2.基类的成员函数在派生类重载。有3种编译区分方法:

(1)根据参数的特征加以区分

例如:Show(int,char);与Show(char *,float);不是同一函数,编译能够区分

(2)使用“::”加以区分

例如:A::Show();有别于B::Show();

(3)根据类对象加以区分

例如:Aobj.Show();调用A::Show();

Bobj.Show();调用B::Show();

 1 #include <iostream>
 2 
 3 class A
 4 {
 5 public:
 6     void go()
 7     {
 8         std::cout << "A->go" << std::endl;
 9     }
10     void go(int num)
11     {
12         std::cout << "A->go" << " " << num << std::endl;
13     }
14     void go(char *str)
15     {
16         std::cout << "A->go" << " " << str << std::endl;
17     }
18 };
19 
20 class B :public A
21 {
22 public:
23     void go()
24     {
25         std::cout << "B->go" << std::endl;
26     }
27 };
28 
29 
30 void main()
31 {
32     B *pb = new B;
33 
34     pb->A::go(NULL);
35     pb->A::go("123");
36     
37     system("pause");
38 }

重载函数的区分

//非const函数一般适用于变量对象

//const函数重载一般适用于常量对象

 1 #include <iostream>
 2 
 3 class A
 4 {
 5 public:
 6     void go()
 7     {
 8         std::cout << "A->go" << std::endl;
 9     }
10     void go(int num)
11     {
12         std::cout << "A->go" << " " << num << std::endl;
13     }
14     void go(char *str)
15     {
16         std::cout << "A->go" << " " << str << std::endl;
17     }
18 };
19 
20 class B :public A
21 {
22 public:
23     void go()//非const函数一般适用于变量对象
24     {
25         std::cout << "B->go" << std::endl;
26     }
27     void go() const//const函数重载一般适用于常量对象
28     {
29         std::cout << "B->go const" << std::endl;
30     }
31 };
32 
33 void main()
34 {
35     B *p = new B;
36     p->go();
37 
38     const B *pb = new B;
39     pb->go();
40         
41     system("pause");
42 }
原文地址:https://www.cnblogs.com/denggelin/p/5668803.html