Menu
CoddyTech

虚分派

Coddy 面向 C 开发者的 C++ 课程的第 39 课,共 48 课。

C 可以通过函数指针模拟分派,但没有语言级的类继承。C++ 虚函数会通过基类引用或指针选择重写的函数。通过基类指针删除派生类对象,需要基类析构函数是虚函数。按值传递多态对象可能会切掉派生部分。

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
const char* ding(void){return "ding";}struct Sound{const char*(*play)(void);};
int main(void){
struct Sound s={ding};puts(s.play());
return 0;
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Sound{virtual ~Sound()=default;virtual std::string play()const{return "tap";}};struct Chime:Sound{std::string play()const override{return "ding";}};
int main(){
Chime x;const Sound& s=x;std::cout<<s.play()<<"\n";
}

分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这个概念;不能假定源程序和目标程序的输出相同。

challenge icon

挑战

简单

输入:基础费用和奖金,均为非负数。Fee.amount 返回基础费用。ExtraFee 公有继承自 Fee,并重写 amount 以加上奖金。驱动程序通过 const Fee 引用调用。使用虚析构函数。

可编辑模块:Fee.cpp、Fee.hpp、ExtraFee.cpp、ExtraFee.hpp。每种必需类型都有各自命名的头文件和实现文件。保留所有公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在有说明的地方独立检查公开 API 的行为。在 API 内返回值,而不是打印。整数输入和结果都适合有符号 int;除非另有说明,文本均为 ASCII。

亲手试试

#include "Fee.hpp"
#include "ExtraFee.hpp"
#include <iostream>
int main(){
{Fee a(5);ExtraFee b(2,7);const Fee& r=b;if(a.amount()!=5||r.amount()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;ExtraFee f(a,b);const Fee& ref=f;std::cout<<ref.amount()<<"\n";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 C++中的所有课

自己练习: C++ 在线编译器