new_point <- function(x, y) {
structure(list(x = x, y = y), class = "Point")
}
point1 <- new_point(1, 2)
point2 <- new_point(2, 3)
# 方法定义在类的外部:新增的方法对先前创建的点同样有效
distance_to <- function(p1, p2) {
UseMethod("distance_to")
}
distance_to.Point <- function(p1, p2) {
sqrt((p1$x - p2$x)^2 + (p1$y - p2$y)^2)
}
# 内置类也用同样的方式扩展
distance_to.numeric <- function(p1, p2) {
abs(p1 - p2)
}
distance <- distance_to(point1, point2)
# distance = 1.414214
number_distance <- distance_to(2, 7)
# number_distance = 5
cat("distance =", distance, "\n")
cat("number_distance =", number_distance, "\n")