3

我试图通过以下示例在其他两个参考类对象(例如,两个足球 [football] 球员)之间“传递”对参考类对象(例如球)的引用:

# create Reference classes
b <- setRefClass('Ball', fields = list(size = 'numeric'))

    p <- setRefClass('Player', fields = list(name = 'character', possession = 'Ball'), 
methods = list(pass = function(){
        tmp <- possession$copy()
        possession <<- NULL
        return(tmp)
    }, receive = function(newBall){
        possession <<- newBall
} 
))


# initialize pretend all-star team
# p1 gets initial possession of a new ball
p1 <- p$new(name = 'Ronaldinho', possession = b$new(size=5) )

p2 <- p$new(name = 'Beckham')

# now pass the ball from p1 to p2
p2$receive(p1$pass())

但是我收到以下错误:

Error in function (value)  : 
  invalid replacement for field ‘possession’, should be from class “Ball” or a subclass (was class “NULL”)

从理论上讲,我试图重新引用对球对象的引用,然后将该引用添加到其他玩家,但显然这不起作用。我知道可以通过直接访问字段来获得相同的结果,但我想找到一种方法来仅使用类的内部方法来完成此“通过”。这可能吗?为什么我会收到此错误?

4

1 回答 1

1

您可能会收到错误,因为在定义Player类时,您将possession字段设置为 type Ball。但是在你的pass函数中,你设置possession为 NULL:

possession <<- NULL

如果将初始化更改为:

p = setRefClass('Player', fields = list(name = 'character', possession = 'ANY')

然后一切都按预期工作:

R> p2$receive(p1$pass())
R> p1
Reference class object of class "Player"
Field "name":
[1] "Ronaldinho"
Field "possession":
NULL
R> p2
Reference class object of class "Player"
Field "name":
[1] "Beckham"
Field "possession":
Reference class object of class "Ball"
Field "size":
[1] 5
于 2013-02-25T09:17:41.820 回答