this 指针

this 指针

this 指针是只能在 class、struct 或 union 类型的非静态成员函数中访问的指针。 它指向为其调用成员函数的对象。 非静态成员函数不具有 this 指针。

语法

this

this->member-identifier

备注

对象的 this 指针不是对象本身的一部分。 它不是对象上 sizeof 语句的结果的一部分。 当对某个对象调用非静态成员函数时,编译器会将该对象的地址作为隐藏的参数传递给函数。 例如,以下函数调用:

myDate.setMonth( 3 );

可以解释为:

setMonth( &myDate, 3 );

对象的地址可从成员函数的内部作为 this 指针提供。 this 指针的大多数使用都是隐式的。 在引用 class 的成员时使用显式 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

#include

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 operator

myBuf = yourBuf;

// Display 'your buffer'

myBuf.Display();

}

my buffer

your buffer

this 指针的类型

this 指针的类型根据函数声明是否包括 const 和/或 volatile 关键字而更改。 以下语法描述了成员函数中 this 的类型:

.- .

成员函数的声明符会确定 cv-qualifier-list。 它可以是 const 或 volatile(或两者)。 class-type 是 class 的名称。

无法重新分配 this 指针。 成员函数声明中使用的 const 或 volatile 限定符适用于由该函数范围中的 this 指针指向的 class 实例,如下标所示:

成员函数声明

this 指针的类型为 class 命名为 myClass

void Func()

myClass *

void Func() const

const myClass *

void Func() volatile

volatile myClass *

void Func() const volatile

const volatile myClass *

下表介绍了有关 const 和 volatile 的详细信息。

this 修饰符的语义

修饰符

含义

const

无法更改成员数据;无法调用不是 const 的成员函数。

volatile

每当访问成员数据时,都会从内存中加载该数据;禁用某些优化。

将 const 对象传递给不是 const 的成员函数是错误的。

同样,将 volatile 对象传递给不是 volatile 的成员函数也是错误的。

声明为 const 的成员函数无法更改成员数据。 在 const 函数中,this 指针是指向 const 对象的指针。

注意

构造函数和析构函数不能声明为 const 或 volatile。 但是,可以在 const 或 volatile 对象上调用它们。

另请参阅

关键字

相关推荐

伤天害理的意思
365bet备用

伤天害理的意思

📅 06-27 👁️ 2616
伤天害理的意思
365bet备用

伤天害理的意思

📅 06-27 👁️ 2616
御剑情缘姻缘系统玩法指南 御剑情缘如何结婚离婚