C++学习笔记-纯虚函数 = 0(接口)

C++中的纯虚函数就可以理解成其他语言中的接口,纯虚函数必须被子类实现,纯虚函数类不允许被实例化,因为它没有具体实现。

纯虚函数演示

 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
class Printable
{
public:
	virtual std::string GetClassName() = 0; // = 0 就表示没有方法体,表示这是一个纯虚函数。
};

// 纯虚函数子类必须实现,没有实现纯虚函数子类就不能实例化
class Entity : public Printable
{
public:
	std::string GetClassName() override { return "Entity"; }
};

// 纯虚函数子类必须实现,没有实现纯虚函数子类就不能实例化
class Player : public Printable
{
public:
	std::string GetClassName() override { return "Player"; }
};

void Print(Printable* printable)
{
	std::cout << printable->GetClassName() << std::endl;
}

int main()
{
	//Printable* printable = new Printable(); // 纯虚函数类不允许被实例化,因为它没有具体实现。

	Entity* entity = new Entity();
	Player* player = new Player();
	Print(entity);
	Print(player);
}

总结

  1. 纯虚函数允许我们在基类中定义一个没有实现的函数,然后强制子类去实现该函数。
  2. 子类如果没有实现纯虚函数就无法实例化。
updatedupdated2025-03-132025-03-13