2015-06-25 136 views
1

我有一個類有字段,我想調用這個類的方法,並獲得對其中一個字段(不是值!!)的引用。事情是這樣的:返回int參考vala

class Test : Object{ 
    uint8 x; 
    uint8 y; 
    uint8 z; 

    uint8 method(){ 
     if (x == 1){ 
      return y; 
     }else if (x == 2){ 
      return z; 
     } 
    } 

    public static void main(string[] args){ 
     uint8 i = method(); // get reference to y or z 
     i++; //this must update y or z 
    } 
} 

在C是:

int& method() 
{ 
    if (x == 1){ 
     return y; 
    }else if (x == 2){ 
     return z; 
    } 
} 

我怎樣才能在VALA實現這一目標?

編輯:我試圖使用指針,我有以下

public class Test : Object { 

    private Struct1 stru; 

    struct Struct1{ 
     uint8 _a; 


     public uint8 a{ 
      get{ return _a; } 
      set{ _a = value; } 
     } 


     public Struct1(Struct1? copy = null){ 
      if (copy != null){ 
       this._a = copy.a; 
      }else{ 
       this._a = 0; 
      } 
     } 

     public uint8* get_aa(){ 
      return (uint8*)a; 

     } 
    } 

    public void get_pointer(){ 
     uint8* dst = stru.get_aa(); 
    } 

    public static int main (string[] args){ 


     Test t = new Test(); 

     return 0; 
    } 

} 

但我編譯時得到

/home/angelluis/Documentos/vala/test.vala.c: In function ‘test_struct1_get_aa’: 
/home/angelluis/Documentos/vala/test.vala.c:130:11: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 
    result = (guint8*) _tmp1_; 
     ^
Compilation succeeded - 2 warning(s) 

爲什麼?我正在返回一個uint8 *類型,並試圖將它存儲在uint8 *指針中。

回答

3

C沒有引用(C++)。請記住,Vala編譯爲C語言作爲中間語言。

我認爲,只有兩種方式瓦拉做到這一點:

  1. 使用箱式封裝的UINT8值並返回到框中鍵入一個參考。

  2. 使用指針。 (這將打開蠕蟲的明顯指針可以)

編輯:回答你更新的示例代碼問題:

你必須非常小心與鑄造東西,一些指針類型。在這種情況下,C編譯器抓住你的虛假投射併發出警告。

uint8 _a; 

// This property will get and set the *value* of _a 
public uint8 a{ 
    get{ return _a; } 
    set{ _a = value; } 
} 

public uint8* get_aa(){ 
    // Here you are casting a *value* of type uint8 to a pointer 
    // Which doesn't make any sense, hence the compiler warning 
    return (uint8*)a; 
} 

請注意,您無法獲得指向某個屬性的指針或引用,因爲屬性本​​身沒有內存位置。

但是,您可以在這種情況下獲得一個指向該領域_a

public uint8* get_aa(){ 
    return &_a; 
} 

如果你堅持要經過的財產,你必須讓你的財產上的指針操作,以及:

uint8 _a; 

    public uint8* a{ 
     get{ return &_a; } 
    } 

請注意,在這個版本中,我刪除了get_aa()方法,該方法現在相當於a的獲取方法。

此外,由於在這段代碼中屬性返回一個指針,不需要setter,所以你可以取消引用指針來設置值。

+0

我已更新我的問題。我使用指針,但我在問題中解釋了一些警告。謝謝。 – RdlP

+0

@RdlP:我也更新了我的答案。 –