Menu
CoddyTech

S3 继承顺序

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

C++ 的继承和虚函数重写构成了声明式类层次结构,并且可以显式调用基类限定的方法。R S3 则使用有序的类名向量,而 NextMethod 会继续沿着分派链执行。这并不是 C++ 的子对象布局。请测试增强函数是否完全按预期调用下一个实现。

C++

#include <iostream>
struct Base {virtual const char* name()const{return "base";}virtual ~Base()=default;};
struct Child:Base {const char* name()const override{return "child";}};

int main() {
    Child c;const Base& b=c;std::cout<<b.name()<<"\n";
}

R

sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")

S3 类的顺序会影响分派链。

challenge icon

挑战

简单

定义泛型 fee(x)。它的 parcel 方法返回 x$units*2。它的 urgent 方法返回 NextMethod()+5。当输入标志为 1 时,适配器会创建类 c("urgent","parcel");否则创建类 parcel。输入内容是非负的单位数,后面跟着标志 0 或 1。

保留已声明的公共 API。可见的锁定驱动程序会直接检查该 API,并打印 solve(lines)。输入符合所述约定;所有算术运算的结果都很小且有限。

你的代码要写在 Parcel.R 和 Exercise.R 中。main.R 会按顺序加载依赖项,并包含提供的输入/输出代码;不能编辑它。

亲手试试

source("Parcel.R")
source("Exercise.R")
stopifnot(identical(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz icon自我测试

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

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

自己练习: R 在线编译器