2012-11-16 58 views
1

我想知道是否有一種方式在C++知道什麼叫一個函數?像Java或JavaScript中的this關鍵字一樣。如何引用C++中的函數?

例如,我有一個名爲insert的函數,它將一個項插入鏈表中,我希望調用那些函數insert的鏈表調用兩個其他函數。我會怎麼做?

我現在有這個權利,這有效嗎?

bool linked_list::insert(int i) 
{ 
    bool inserted = false; 

    if(this.is_present(i)) /* function is_present is defined earlier checks if an int is already in the linked-list. */ 
    { 
     inserted = true // already inside the linked-list 
    } 
    else 
    { 
     this.Put(0, i); /* function Put is defined earlier and puts an int in a linked-list at a given position (first param.). */ 
     inserted = true; // it was put it. 

    } 
return inserted; 
} 
+0

您的術語有點不正確。鏈表不調用'insert';在鏈表上調用'insert'。該函數被其他使用它的函數調用。 –

回答

2

對於historical reasonsthis是一個指針。使用->而不是.

bool linked_list::insert(int i) { 
    bool inserted = false; 

    if(this->is_present(i)) { 
     inserted = true; // fixed syntax error while I was at it. 
    } else { 
     this->put(0, i); // fixed inconsistent naming while I was at it. 
     inserted = true; 
    } 
    return inserted; 
} 

通常根本不需要使用this->;你可以做if(is_present(i))

0

你爲什麼不直接調用linked_list::insert(int)中的其他函數?不,它是無效的,你應該把this -> something,而不是this.something

1

this在C++中的工作方式與它在Java中的工作方式相同。唯一的區別是您需要使用this->而不是this.this是一個指針,因此您不能使用點運算符來訪問它的成員。