C++FAQ

Monday, January 30, 2006

 

'this'指標是什麼?

Q: 'this'指標是什麼?

A: 一般人很容易誤以為'this'指標是一個class或struct的隱函成員。實際上它是non-static member function的隱藏參數。當你宣告一個function時,Compiler會自動在前面加上這個參數到你function的prototype中。這個參數的形別是根據你在如何宣告你的function。根據C++標準,9.3.2.1中所提到:

在nonstatic member function中,關鍵字'this'是一個non-lvalue expression,它的值是目前呼叫此function的物件之記憶體位置。若此function是宣告在class X中,則這個'this'的形別就是X*。若這個member function是被宣告為const,則此'this'的形別就是const X*,如果這個function宣告為volatile,則這個'this'的形別就是volatile X*,如果這個function被宣告為const volatile,則此'this'的形別就是const volatile X*。

比如說:
class T
{
public:
void foo(int a);
int goo() const;
};
實際上是:
class T
{
public:
void foo(T* this , int a);
int goo(const T* this) const;
};
Static member function不會有這個額外的參數。你不能使用non-static member function做為thread function,即使它有正確的prototype。(One consequence is that you cannot use a non-static member function as a thread function even if it has the correct prototype,不太確定對不對)

比如:
UINT ThreadFunction(LPVOID param);

因為上述的理由,會變成:
UINT ThreadFunction(T* this, LPVOID param);



Comments: Post a Comment



<< Home

Archives

January 2006   February 2006  

This page is powered by Blogger. Isn't yours?