如何在R中创建虚拟引用类?

mch*_*hen 6 oop r class reference-class

我在虚拟/抽象类中找不到多少help(ReferenceClasses)- 有人能提供创建一个基本的例子吗?此外,如何指定虚方法并强制子类必须实现它?

ags*_*udy 5

参考类是S4类。因此,也许您应该看到setClassand 的帮助Classes

这里是一个虚拟的例子:

# virtual Base Class
setRefClass( 
  Class="virtC", 
  fields=list( 
    .elt="ANY" 
  ),
  methods = list(
    .method = function(){
      print("Base virtual method is called")
    }
  ), 
  contains=c("VIRTUAL") 
) 

## child 1
## field as char and .method is overwritten
setRefClass( 
  Class="childNum", 
  fields=list( 
    .elt="numeric" 
  ), 
  contains=c("virtC")  
)


## child 2 
## field is numeric and base .method is used
setRefClass( 
  Class="childChar", 
  fields=list( 
    .elt="character" 
  ), 
  methods = list(
    .method = function(){print('child method is called')}
  ), 
  contains=c("virtC") 
) 
##  new('virtA')          ## thros an error can't isntantiate it
a = new("childChar",.elt="a")
b =   new("childNum",.elt=1)

b$.method()
[1] "Base virtual method is called"

a$.method()
[1] "child method is called"
Run Code Online (Sandbox Code Playgroud)