2012-01-07 24 views
0

itcl::scope返回指定成員變量$this的全名。如何爲當前類的任意對象調用itcl :: scope?

如何爲同一類的另一個對象(不是$this)調用itcl::scope

這是一種解決方法。

itcl::class dummy { 
    variable m_data 

    method function { other } { 
     if { [itcl::is object -class dummy $other] } { 
      error "Invalid argument." 
     } 

     set name "@itcl $other [$other info variable m_data -name]" 
     # OR 
     set name [lreplace [itcl::scope m_data] 1 1 $other] 

     puts "==== this is the name of m_data of of object $other: $name" 
    } 
} 

但是,這是醜陋的,說得溫和。

我想$other info variable m_data -name應該返回我想要的,但它只是省略了對象的上下文。

回答

0

有沒有一種很好的方式來獲得這些信息,也不一定是一件好事。通常將對象的變量視爲該對象的實現的一部分,而不是其接口的一部分。因此,外部代碼不應該像這樣在內部徘徊;如果對象外部(包括類的其他成員)訪問變量很重要,請編寫一個方法將引用返回給變量(如itcl::scope生成的那樣)。

itcl::class dummy { 
    variable m_data 

    protected method dataRef {} { itcl::scope m_data } 

    method function { other } { 
     if { [itcl::is object -class dummy $other] } { 
      error "Invalid argument." 
     } 

     set name [$other dataRef] 

     puts "==== this is the name of m_data of of object $other: $name" 
    } 
} 
+0

當然,成員變量應該是實現的一部分,而不是接口。但是一個類的成員函數必須能夠看到該類的所有對象的成員變量(不僅是'$ this'對象的成員變量)。 – Vahagn 2012-01-13 21:46:27

+0

@Vahagn:這是我不是100%確定的,我同意。雖然我不知道如何在這個主題上撰寫整篇文章,但我今天沒有時間這樣做,但是如何表達我的問題呢...... – 2012-01-16 10:40:24

相關問題