1

我想将引用类传递给引用类构造函数,并将传递的引用类分配为字段。但是,当我运行下面的代码时,我不明白为什么会出现错误。我的问题是:

1)请有人可以解释为什么会发生此错误:

> a <- ClassA&new()
Error in .getClassFromCache(Class, where) : 
  argument "Class" is missing, with no default
> b <- ClassB$new(a)
Error in .Object$initialize(...) : object 'a' not found

2) 我已将class.a.container声明为类“列表”,但是我希望这是一个参考类。我需要在这里放什么而不是“列表”?

ClassA <- setRefClass(
  "ClassA",

  fields = list(myVar = "numeric"),

  methods = list(
    someMethod = function(){
      print("hi")
    }
  )
)

ClassB <- setRefClass(
  "ClassB",

  fields = list(class.a.container = "list"),

  methods = list(
    initialize = function(class.a){
      class.a.container <<- class.a
  })
)

a <- ClassA&new()
b <- ClassB$new(a)
4

2 回答 2

5

你会觉得有点傻,至少当我注意到这个问题时我做到了。在从 environment-class-item 中提取时,您有一个美元符号的 & 符号。

a <- ClassA$new(myVar=1)
a$someMethod(2)
#[1] "hi
于 2012-10-31T21:47:16.190 回答
1

42- 已经在你的代码中指出了一个错误(& 而不是 $)。

为了完全回答您的原始问题,我只想明确指出,在纠正该错误后,您需要将 ClassB 中的字段声明从

class.a.container = "list"

class.a.container = "ClassA"

这是对我有用的完整代码:

ClassA = setRefClass(
    Class = "ClassA",

    fields = list(myVar = "numeric"),

    methods = list(
        someMethod = function() {
            print("hi")
        }
    )
)

ClassB = setRefClass(
    Class = "ClassB",

    fields = list(class.a.container = "ClassA"),

    methods = list(
        initialize = function(class.a) {
            class.a.container <<- class.a
        }
    )
)

a = ClassA$new(myVar = 1)
a

b = ClassB$new(a)
b

它打印:

...
> a
Reference class object of class "ClassA"
Field "myVar":
[1] 1
> 
> b = ClassB$new(a)
> b
Reference class object of class "ClassB"
Field "class.a.container":
Reference class object of class "ClassA"
Field "myVar":
[1] 1
于 2016-12-01T14:53:42.920 回答