[英]What does “this” refer to exactly in this code?
public CharList(CharList l)
{
// Whatever method your CharList provides to get the
// first node in the list goes here
CharNode pt = l.head();
// create a new head node for *this* list
CharNode newNode = new CharNode();
this.head = newNode;
// Go through old list, copy data, create new nodes
// for this list.
while(pt != null)
{
newNode.setCharacter(pt.getCharacter());
pt = pt.getNext();
if (pt != null)
{
newNode.setNext(new CharNode());
newNode = newNode.getNext();
}
}
}
我以為這是在“ A.addElement(car);”中用來指代對象A的,但是在這種情況下,我不知道它指的是什么...而且我看不出這樣做的意義:this.head = newNode; 因為this.head不再使用。
this
指向CharList
的當前實例, this.head
指向實例字段head
。 如果沒有同名的本地變量,則可以放棄this
關鍵字來訪問實例字段。
該文檔解釋了這是什么:
在實例方法或構造函數中,這是對當前對象的引用-當前對象正在調用其方法或構造函數。 您可以使用此方法從實例方法或構造函數中引用當前對象的任何成員。
關鍵字this
指向CharList
的當前實例。 對於引用可能在類級別共享相同變量的變量很有用,否則可以省略。
在這里, CharList
的構造函數中沒有局部變量head
,所以可以這樣寫:
head = newNode;
this.head不再使用。
由於head
是該類的成員變量,因此在構造函數中設置的值將在該類的其他方法中使用。
Java中“ this”的含義的可能重復項? , 但無論如何:
它是對您正在使用的對象的特定實例的引用。 因此,如果我有(對不起,請使用C#編寫):
public class MyObject
{
public MyObject(string AString)
{
MyString = AString;
}
private string MyString;
public string WhatsMyStringCalled()
{
return this.MyString;
}
}
如果要構造MyObject的實例,我希望WhatsMyStringCalled返回與該特定實例關聯的MyString屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.