第二,任何派生类必须定义为该函数体,或将派生类是抽象基类,以及。
让我们采取行动在一个纯虚函数的一个例子看看。在前一课中,我们写了一个简单的动物的基类和派生类中的一只猫和一只狗班。这里的代码我们离开这:
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
#include <string>
class Animal
{
protected:
std::string m_strName;
// We're making this constructor protected because
// we don't want people creating Animal objects directly,
// but we still want derived classes to be able to use it.
Animal(std::string strName)
: m_strName(strName)
{
}
public:
std::string GetName() { return m_strName; }
virtual const char* Speak() { return "???"; }
};
class Cat: public Animal
{
public:
Cat(std::string strName)
: Animal(strName)
{
}
virtual const char* Speak() { return "Meow"; }
};
class Dog: public Animal
{
public:
Dog(std::string strName)
: Animal(strName)
{
}
virtual const char* Speak() { return "Woof"; }
};
我们已经阻止了人们从分配对象类型的构造函数保护动物。然而,有一个问题还没有得到解决。它仍然是可能创建派生类没有重定义speak()。例如: