this 指针的类型

通过 const 和 volatile 关键字,可以在函数声明中修改 this 指针的类型。 若要将函数声明为具有一个或多个关键字的特性,请将关键字添加到函数参数列表的后面。

请看以下示例:

// type_of_this_pointer1.cpp
class Point
{
    unsigned X() const;
};
int main()
{
}

上面的代码声明一个成员函数 X,其中,this 指针被视为指向 const 对象的 const 指针。 可以使用 cv-mod-list 选项的组合,但它们始终通过 this 修改指向的对象,而不是 this 指针本身。 因此,以下声明将声明函数 X;this 指针是指向 const 对象的 const 指针:

// type_of_this_pointer2.cpp
class Point
{
    unsigned X() const;
};
int main()
{
}

成员函数中的 this 类型由以下语法描述,其中,cv-qualifier-list 是从成员函数声明符中确定的,且可以是 constvolatile(或两者),并且 class-type 是类的名称:

[cv-qualifier-list] class-type * const this

换言之,this 始终是 const 指针;无法重新指派它。用于成员函数声明中的 const 或 volatile 限定符通过该函数范围中的 this 应用于所指向的类实例。

下表介绍了有关这些修饰符的工作方式的更多信息。

this 修饰符的语义

修饰符

含义

const

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

volatile

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

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

声明为 const 的成员函数不能更改数据成员 - 在此类函数中,this 指针是指向 const 对象的指针。

备注

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

请参见

参考

this 指针