抽象类
发表于:2024-12-18 | 分类: C++
字数统计: 302 | 阅读时长: 1分钟 | 阅读量:

抽象类

纯虚函数

=0表示他是纯虚函数,没有函数实体

1
virtual 返回值类型 函数名 (函数参数) = 0;

抽象类

  • 包含纯虚函数的类就是抽象类
  • 抽象类不能创建对象(包含纯虚函数【无实体】),无法分配内存
  • 只能创建创建派生类对象(需要实现纯虚函数实体)

案例

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
using namespace std;

// 抽象基类
class Animal
{
public:
// 纯虚函数,派生类必须重写它
virtual void makeSound() const = 0;

// 可以有普通的成员函数
void eat() const
{
cout << "This animal is eating." << endl;
}

// 虚析构函数,确保派生类对象被正确析构
virtual ~Animal() {}
};

// 派生类:Dog
class Dog : public Animal
{
public:
void makeSound() const
{
cout << "汪汪!" << endl;
}
};

// 派生类:Cat
class Cat : public Animal
{
public:
void makeSound() const override
{
cout << "喵喵!" << endl;
}
};

int main()
{
// 多态:使用基类指针指向派生类对象
Animal *dog = new Dog();
Animal *cat = new Cat();

// 调用重写的纯虚函数
dog->makeSound();
cat->makeSound();

// 调用普通成员函数
dog->eat();
cat->eat();

// 释放内存
delete dog;
delete cat;

return 0;
}
上一篇:
模板
下一篇:
ubuntu 没有IP地址