2012-11-17 30 views
2

我已經寫了兩個類第一個成員和第二個商店。我寫了一個方法,可以從成員類創建一個對象,我試圖在類成員類中寫入Store類型的字段存儲,我希望它存儲成員輸入的存儲的引用。 有人告訴我這樣做: memberRegister()需要傳遞一個指向當前存儲對象的指針。請幫我用自我參考指針

實際上,Store對象需要能夠告訴會員對象「指向我」。也就是說,Store對象需要一個指向它自己的指針。 但我沒有得到它

這是會員類

private int pinNumber; 
private String name, id; 
private Store store; 


/** 
* Constructor for objects of class Member 
*/ 
public Member(String name, String id, int pinNumber, Store store) 

{ 
    // initialise instance variables 
    this.name = name; 
    this.id = id; 
    this.pinNumber = pinNumber; 
    checkId(); 
    checkPinNumber(); 
} 

/** 
* An example of a method - replace this comment with your own 
* 
* @param y a sample parameter for a method 
* @return  the sum of x and y 
*/ 
private void checkId() 
{ 
    // put your code here 
    int length; 
    length = id.length(); 
    if (length > 10){ 
     System.out.println("lentgh must be at 10 "); 
    } 
} 
private void checkPinNumber() 
{ 
    int length; 
    length = id.length(); 
    if ((length > 4) && (length < 4)){ 
     System.out.println("lentgh must be at 4"); 
} 

類店

private String storeName; 
private int total; 
private Member member; 


/** 
* Constructor for objects of class Store 
*/ 
public Store(String storeName, int total) 
{ 
    // initialise instance variables 
    this.storeName = storeName; 
    this.total = total; 
} 

/** 
* 
*/ 
public String getStoreName() 
{ 
return storeName; 
} 

/** 
* An example of a method - replace this comment with your own 
* 
* @param y a sample parameter for a method 
* @return  the sum of x and y 
*/ 
public Member memberRegister(String name, String id, int pinNumber) 
{ 
    // put your code here 
    Member member; 
    member = new Member(name, id, pinNumber) 
    return member; 
} 
+1

這個'不夠'嗎?即'返回新成員(名稱,ID,PINNumber,這個);'? –

+0

@Kerrek這會做,如果構造函數將商店存儲在它的私有成員變量,它不這樣做。 –

回答

1

您memberRegister方法不正確地調用您的會員構造:

public Member memberRegister(String name, String id, int pinNumber) 
{ 
    // put your code here 
    Member member; 
    member = new Member(name, id, pinNumber, this) //this passes in a reference to your store 
    return member; 
} 

然後,在您的會員構造函數中分配參考:

public Member(String name, String id, int pinNumber, Store store) 

{ 
    // initialise instance variables 
    this.name = name; 
    this.id = id; 
    this.store = store //where this.store is a Store 
    this.pinNumber = pinNumber; 
    checkId(); 
    checkPinNumber(); 
} 

希望有所幫助。順便說一句,更新評論的方式,他們匹配你的代碼。

0

見你的情況傳遞this關鍵字方法memberRegisteruseless

returningthis關鍵字useful

瞭解更多有關此關鍵字的check this

1

使用關鍵字this是你如何能得到一種自我指涉的指針。您應該能夠按照@Kerrek SB的建議進行操作,並且memberRegister方法中可以使用return new Member(name, id, pinNumber, this)