C++ 纯虚函数
【摘要】
C++ 纯虚函数
概述纯虚函数例子
概述
纯虚函数 (pure virtual function) 是只有函数的名字而不具备函数的功能, 不能被调用的虚成员函数.
基类的虚函数有时是考虑...
概述
纯虚函数 (pure virtual function) 是只有函数的名字而不具备函数的功能, 不能被调用的虚成员函数.
基类的虚函数有时是考虑到派生类的需求, 在基类中预留一个函数名. 我们在设计类的时候, 常常有基类的成员函数并无意义, 具体功能由派生类决定, 这时候纯虚函数就派上用场了.
纯虚函数
纯虚函数没有函数体, 最后面的 “=0” 只起形式上的作用, 告诉编译系统 “这是纯虚函数”.
格式:
virtual 函数类型 函数名 (参数表列) =0;
- 1
例如:
virtual float area()=0; // 纯虚函数
virtual float area() const =0; // 纯虚常函数
virtual float area() const {return 0}; // 虚函数
- 1
- 2
- 3
如果一在一个类中声明了纯虚函数, 而在其派生类中没用对该函数定义, 则该函数在派生类中仍为纯虚函数.
例子
Animal 类:
#ifndef PROJECT6_ANIMAL_H
#define PROJECT6_ANIMAL_H
#include <iostream>
using namespace std;
class Animal {
public:
virtual void bark() = 0;
};
#endif //PROJECT6_ANIMAL_H
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
Dog 类:
#ifndef PROJECT6_DOG_H
#define PROJECT6_DOG_H
#include "Animal.h"
class Dog : public Animal{
public:
void bark() {
cout << "汪汪!" << endl;
}
};
#endif //PROJECT6_DOG_H
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Cat 类:
#ifndef PROJECT6_CAT_H
#define PROJECT6_CAT_H
#include "Animal.h"
class Cat : public Animal{
public:
void bark() {
cout << "喵喵!" << endl;
}
};
#endif //PROJECT6_CAT_H
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Pig 类:
#ifndef PROJECT6_PIG_H
#define PROJECT6_PIG_H
#include "Animal.h"
class Pig : public Animal {
public:
void bark() {
cout << "哼哼!" << endl;
}
};
#endif //PROJECT6_PIG_H
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
main:
#include <iostream>
#include "Animal.h"
#include "Dog.h"
#include "Cat.h"
#include "Pig.h"
using namespace std;
int main() {
Animal *pt;
Dog d1;
Cat c1;
Pig p1;
pt = &d1;
pt->bark();
pt = &c1;
pt->bark();
pt = &p1;
pt->bark();
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
输出结果:
汪汪!
喵喵!
哼哼!
- 1
- 2
- 3
文章来源: iamarookie.blog.csdn.net,作者:我是小白呀,版权归原作者所有,如需转载,请联系作者。
原文链接:iamarookie.blog.csdn.net/article/details/116836843
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)