CPP学习之——三种调用虚函数的方式比较(13.9)

一 概述

本节课讲述使用对象、指针和引用三种方式调用虚函数,并观察输出结果

二 示例演示及结果输出

2.1 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
using namespace std;
class father
{
public:
virtual void run() const {cout << "父亲可以跑万米" << endl;}
};
class son: public father
{
public:
void run() const {cout << "儿子可以跑十万米" << endl;}
};
class daughter: public father
{
public:
void run() const {cout << "女儿可以跑五万米" << endl;}
};
void one(father one);
void two(father *two);
void three(father &three);
int main()
{
father *p = 0;
int choice;
while (1)
{
bool quit = false;
cout << "(0)quit(1)son(2)daughter(3)father:";
cin >> choice;
switch (choice) {
case 0:
quit = true;
break;
case 1:
p=new son;
one(*p);
break;
case 2:
p=new daughter;
two(p);
break;
case 3:
p=new father;
three(*p);
break;
default:cout<<"请输入0到3之间的数字"<<endl;
}
if(quit){
break;
}
}
return 0;
}
void one(father one) {one.run();}
void two(father *two) {two->run();}
void three(father &three) {three.run();}

2.2 输出结果

1
2
3
4
5
6
7
(0)quit(1)son(2)daughter(3)father:1
父亲可以跑万米
(0)quit(1)son(2)daughter(3)father:2
女儿可以跑五万米
(0)quit(1)son(2)daughter(3)father:3
父亲可以跑万米
(0)quit(1)son(2)daughter(3)father:

2.3 代码说明

  • 使用指针方式的能够达到预期的结果