this总是指向当前对象,每次执行成员函数时,形如本例中的SetColor(int _color),总是会被编译成SetColor(CTestThis* this, int _color),编译器会自动带入对象地址作为this指针所指向的地址,本例中的全局函数也许可以加深对this指针的理解。
-
#include <iostream>
-
-
class CTestThis
-
{
-
public:
-
int GetColor ( ) { return this->color; }
-
void SetColor ( int _color ) { this->color = _color; }
-
void Display ( ) { std:: cout << this->color << std:: endl; }
-
-
private:
-
int color;
-
};
-
-
void SetColor ( int _color, CTestThis* _ )
-
{
-
_->SetColor (_color );
-
}
-
-
void Display (CTestThis* _ )
-
{
-
std:: cout << _->GetColor ( ) << std:: endl;
-
}
-
-
void main ( void )
-
{
-
CTestThis test;
-
-
test. SetColor ( 3 );
-
test. Display ( );
-
-
SetColor ( 33, &test );
-
Display (&test );
-
-
system ( "pause" );
-
}