在函数声明时加virtual
virtual void display();
实现用基类指针访问派生类函数
要把基类的析构函数声明为
虚函数
这是因为当通过 动态方式 建立 对象的时候,当使用多态性,利用基类指针指向 派生类,那么当对指向派生类的基类指针 使用delete,如果析构函数不是虚基类,则仅仅调用基类的 析构函数,而不是调用派生类的析构函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#include<iostream>
using
namespace
std;
class
ClxBase{
public
:
ClxBase() {};
~ClxBase() {cout <<
"Output from the destructor of class ClxBase!"
<< endl;};
void
DoSomething() { cout <<
"Do something in class ClxBase!"
<< endl; };
};
class
ClxDerived :
public
ClxBase{
public
:
ClxDerived() {};
~ClxDerived() { cout <<
"Output from the destructor of class ClxDerived!"
<< endl; };
void
DoSomething() { cout <<
"Do something in class ClxDerived!"
<< endl; };
};
int
main(){
ClxBase *p =
new
ClxDerived;
//基类指针,指向派生类
p->DoSomething();
delete
p;
//这里因为析构函数不是虚函数,所以仅仅调用基类 的 析构函数
return
0;
}
|
这段代码输出如下:
![567993-20160318171956771-1643514935.png](https://i-blog.csdnimg.cn/blog_migrate/0b2fa190834eff48d96fc895c54fac03.png)
构造函数不能声明为虚函数