R引用类作为引用类的字段

时间:2012-10-31 19:14:39

标签: r oop reference-class

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

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 声明为类“list”,但我希望这是一个引用类。我需要放在这里而不是“列表”?

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)

2 个答案:

答案 0 :(得分:5)

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

a <- ClassA$new(myVar=1)
a$someMethod(2)
#[1] "hi

答案 1 :(得分:1)

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

要完全回答您的原始问题,我只想明确指出在纠正该错误之后,您需要更改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