虚函数派发
Coddy 面向 R 开发者的 C++ 课程的第 39 课,共 48 课。
R 的 S3 分派始终是动态的:UseMethod() 会在调用时查看实际参数的类向量,而 NextMethod() 会继续使用该向量中的下一个类。C++ 要求使用 virtual,并且在使用基类值时必须避免切片。通过基类指针或引用进行的 C++ virtual 调用会动态分派。多态删除需要虚析构函数;复制到基类值中可能会发生切片。
R
label <- function(x) UseMethod("label")
label.base <- function(x) "base"
label.child <- function(x) paste0(NextMethod(), "!")
obj <- structure(list(), class = c("child", "base"))
cat(label(obj), "\n")
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";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这一概念;不假设源输出与目标输出相同。
挑战
简单输入:基础费用和额外费用,均为非负数。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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 C++中的所有课
自己练习: C++ 在线编译器