forked from Light-City/CPlusPlusThings
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinline_virtual.cpp
More file actions
Latest commit
35 lines (31 loc) · 996 Bytes
/
Copy pathinline_virtual.cpp
File metadata and controls
35 lines (31 loc) · 996 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
#include<iostream>
usingnamespacestd;
classBase
{
public:
inlinevirtualvoidwho()
{
cout << "I am Base\n";
}
virtual~Base() {}
};
classDerived : publicBase
{
public:
inlinevoidwho() // 不写inline时隐式内联
{
cout << "I am Derived\n";
}
};
intmain()
{
// 此处的虚函数 who(),是通过类(Base)的具体对象(b)来调用的,编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
Base b;
b.who();
// 此处的虚函数是通过指针调用的,呈现多态性,需要在运行时期间才能确定,所以不能为内联。
Base *ptr = newDerived();
ptr->who();
// 因为Base有虚析构函数(virtual ~Base() {}),所以 delete 时,会先调用派生类(Derived)析构函数,再调用基类(Base)析构函数,防止内存泄漏。
delete ptr;
return0;
}