虽然这两个例子只使用的猫和狗,其他类我们从动物的工作也将与我们的report()功能和动物阵列不进一步修改!这也许是虚函数,在这样一种方式,新派生的类会自动工作,与旧代码无需修改你的代码的能力结构的最大效益!
一句警告:派生类的函数的签名必须与基类的虚函数的派生类的函数中使用的顺序签名完全匹配。如果派生类函数有不同的参数类型,程序可能仍会编译通过,但是虚拟函数不会解决打算。
利用虚拟关键词
从技术上讲,虚拟的关键词是不是在派生类的需要。比如说呢。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class
Base
{
protected
:
public
:
virtual
const
char
* GetName() {
return
"Base"
; }
};
class
Derived:
public
Base
{
public
:
const
char
* GetName() {
return
"Derived"
; }
// note lack of virtual keyword
};
int
main()
{
Derived cDerived;
Base &rBase = cDerived;
cout <<
"rBase is a "
<< rBase.GetName() << endl;
return
0;
}
|
完全一样,如果来源::getname()被明确标记为虚拟。只有最基类函数需要被标记为虚拟的所有的派生功能工作几乎。然而,有关键词虚拟衍生功能不受伤害,它可以作为一个有用的提示,功能是一个虚拟的功能,而不是一个正常的人。因此,它使用虚拟关键词虚拟化功能的派生类虽然不是严格必要的通常是一个好主意。
虚函数的返回类型
在正常情况下,一个虚拟函数的返回类型和它的覆盖必须匹配。因此,以下将不会工作:
1
2
3
4
5
6
7
8
9
10
11
|
class
Base
{
public
:
virtual
int
GetValue() {
return
5; }
};
class
Derived:
public
Base
{
public
:
virtual
double
GetValue() {
return
6.78; }
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class
Base
{
public
:
// This version of GetThis() returns a pointer to a Base class
virtual
Base* GetThis() {
return
this
; }
};
class
Derived:
public
Base
{
// Normally override functions have to return objects of the same type as the base function
// However, because Derived is derived from Base, it's okay to return Derived* instead of Base*
virtual
Derived* GetThis() {
return
this
; }
};
|