this 指针
this 指针是只能在 class、struct或 union 类型的非静态成员函数中访问的指针。 它指向为其调用成员函数的对象。 静态成员函数没有 this 指针。
this
this->member-identifier
备注
对象的 this 指针不是对象的一部分;它没有在对象上的 sizeof 语句的结果中反映。 相反,当对某个对象调用非静态成员函数时,该对象的地址将由编译器作为隐藏的参数传递给函数。 例如,以下函数调用:
myDate.setMonth( 3 );
可以按以下方式解释:
setMonth( &myDate, 3 );
对象的地址可从成员函数的内部作为 this 指针提供。 this 的大多数使用都是隐式的。 在引用类的成员时显式使用 this 是合法的,但没有必要。 例如:
void Date::setMonth( int mn )
{
month = mn; // These three statements
this->month = mn; // are equivalent
(*this).month = mn;
}
表达式 *this 通常用于从成员函数返回当前对象:
return *this;
this 指针还用于防止自引用:
if (&Object != this) {
// do not execute in cases of self-reference
备注
由于 this 指针无法更改,因此不允许对 this 赋值。C++ 的早期实现允许对 this 赋值。
this 指针有时可直接使用 - 例如,当操作自引用数据结构,而其中需要当前对象的地址时。
示例
// this_pointer.cpp
// compile with: /EHsc
#include <iostream>
#include <string.h>
using namespace std;
class Buf
{
public:
Buf( char* szBuffer, size_t sizeOfBuffer );
Buf& operator=( const Buf & );
void Display() { cout << buffer << endl; }
private:
char* buffer;
size_t sizeOfBuffer;
};
Buf::Buf( char* szBuffer, size_t sizeOfBuffer )
{
sizeOfBuffer++; // account for a NULL terminator
buffer = new char[ sizeOfBuffer ];
if (buffer)
{
strcpy_s( buffer, sizeOfBuffer, szBuffer );
sizeOfBuffer = sizeOfBuffer;
}
}
Buf& Buf::operator=( const Buf &otherbuf )
{
if( &otherbuf != this )
{
if (buffer)
delete [] buffer;
sizeOfBuffer = strlen( otherbuf.buffer ) + 1;
buffer = new char[sizeOfBuffer];
strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer );
}
return *this;
}
int main()
{
Buf myBuf( "my buffer", 10 );
Buf yourBuf( "your buffer", 12 );
// Display 'my buffer'
myBuf.Display();
// assignment opperator
myBuf = yourBuf;
// Display 'your buffer'
myBuf.Display();
}