2015-12-09 85 views
1

我來自一個C++背景,我努力學習R.當我想的對象用C++類來跟蹤另一個已經存在的對象,我想補充一個指針成員。我知道R默認不支持指針,但我需要將該功能添加到我的引用類。參考其他對象作爲參考類別字段

在C++如果我試圖做類似 foo <- setRefClass("foo", fields = list(another = "foo")) 我明明得到Error: evaluation nested too deeply: infinite recursion....,爲R試圖實例化對象我會做類似

class foo 
{ 
public: 
    foo *pAnotherFoo; 
} 

,將實例化另一個等等(我認爲?)。

我不知道是否有某種方式讓R,我不想讓這一領域的實例化,我將在後面的值分配給它。

+1

C不上課。 –

+0

你可能會證明你想用C中的一個(小)例子來做什麼嗎? – nrussell

+0

這似乎並不約爲C編程(也許關於C++編程)建議去掉「C」標籤 – user3629249

回答

0

看來您使用引用類的R.如果是這樣,你可以簡單地定義

foo <- setRefClass('foo', 
     fields = list(anotherObject = 'ANY')) 

正如我敢肯定,你可以猜測,這並沒有執行anotherObjectfoo類的,但沒有理由不能將此值設置爲類foo的對象。事實上,這樣做會加速性能(否則,你的對象將檢查類anotherObject 時候你的目標是改變的)。所以,你需要的參考行爲(無級執行)可以通過

myObj1 <- new('foo') 
myObj2 <- new('foo') 
myObj1$anotherObject <- myObj2 

實現爲了說明引用的行爲,考慮

myObj1$anotherObject$anotherObject <- 1 
myObj2$anotherObject 
[1] 2