-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathvirtual.cpp
More file actions
55 lines (44 loc) · 1002 Bytes
/
virtual.cpp
File metadata and controls
55 lines (44 loc) · 1002 Bytes
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
#include <iostream>
#include<iostream>
using namespace std;
class Employee
{
public:
virtual void raiseSalary()
{
cout<<0<<endl;
}
virtual void promote()
{ /* common promote code */ }
};
class Manager: public Employee
{
void raiseSalary() override
{
cout<<100<<endl;
}
void promote() override
{ /* Manager specific promote */ }
};
class Engineer: public Employee
{
void raiseSalary() override
{
cout<<200<<endl;
}
void promote() override
{ /* Manager specific promote */ }
};
void globalRaiseSalary(Employee *emp[], int n)
{
for (int i = 0; i < n; i++)
emp[i]->raiseSalary();
// according to the actual object, not according to the type of pointer
}
int main()
{
// 虚函数的调用取决于指向或者引用的对象的类型,而不是指针或者引用自身的类型
Employee *emp[] = {new Manager(), new Engineer};
globalRaiseSalary(emp,2); // 100 200
return 0;
}