精益求精

  • 覆盖失败?
  • 如何避免覆盖失败?
  • 缺省参数谁说了算?

虚函数表

缺省参数

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>

class Base
{
public:
virtual void display(const std::string &strShow = "I am Base class !")
{
std::cout << std::endl;
std::cout << strShow << std::endl;
std::cout << "Base display" << std::endl;
}
virtual ~Base()
{
}
};

class Derive : public Base
{
public:
virtual void display(const std::string &strShow = "I am Derive class !")
{
std::cout << std::endl;
std::cout << strShow << std::endl;
std::cout << "Derive display" << std::endl;
}
virtual ~Derive()
{
}
};

class Third : public Derive
{
public:
virtual void display(const std::string &strShow = "I am Third class !")
{
std::cout << std::endl;
std::cout << strShow << std::endl;
std::cout << "Third display" << std::endl;
}
virtual ~Third()
{
}
};

int main()
{
Base *pBase = new Third();
Derive *pDerive = new Third();
Third *pThird = new Third();

Third *pThirdBase = static_cast<Third *>(pBase);
Third *pThirdDerive = static_cast<Third *>(pDerive);

Base *pBaseThird = (Base *)pThird;
Base *pDeriveThird = (Derive *)pThird;

pBase->display();
pDerive->display();
pThird->display();
pThirdBase->display();
pThirdDerive->display();
pBaseThird->display();
pDeriveThird->display();
}

=================================================================================

输出结果:
I am Base class !
Third display

I am Derive class !
Third display

I am Third class !
Third display

I am Third class !
Third display

I am Third class !
Third display

I am Base class !
Third display

I am Base class !
Third display

注: 根据汇编显示,虚函数调用时,压栈的缺省实参与指针类型(非对象实际类型)保持一致。

留言