c++中的this 指针

xiaoxiao2021-02-28  172

介绍

C++中的this指针在类的nonstatic member function 中是一个隐藏的参数,在static member function 中没有this指针.this指针中保存的是调用nonstatic member function的类对象的地址.类的nonstatic member function 之所以会有这个隐藏的参数是因为编译器在调用类的nonstatic member function 时,要将它们转换为普通的nonmember function.为了让编译器区别正在处理的是哪个类对象,所以会将类对象的地址传递nonstatic member function 的this指针,只不过这个this指针是隐藏的,比如:

myDate.setMonth( 3 ); 会被转换为:

setMonth( &myDate, 3 );

this指针类型

The type of this in a member function is described by the following syntax, where cv-qualifier-list is determined from the member functions declarator and can be const or volatile (or both), and class-type is the name of the class:

[cv-qualifier-list] class-type * const this In other words,  this  is always a const pointer; it cannot be reassigned. The  const  or  volatile  qualifiers used in the member function declaration apply to the class instance pointed to by  this  in the scope of that function.

The following table explains more about how these modifiers work.

Modifier Meaning const Cannot change member data; cannot invoke member functions that are not const. volatile Member data is loaded from memory each time it is accessed; disables certain optimizations.

It is an error to pass a const object to a member function that is not const. Similarly, it is an error to pass a volatile object to a member function that is not volatile.(把一个const object传递给一个非constmember function会发生错误 )

Member functions declared as const cannot change member data — in such functions, the this pointer is a pointer to a const object.

在什么情况下使用this指针

When local variable’s name is same as member’s name#include<iostream> using namespace std; /* local variable is same as a member's name */ class Test { private: int x; public: void setX (int x) { // The 'this' pointer is used to retrieve the object's x // hidden by the local variable 'x' this->x = x; } void print() { cout << "x = " << x << endl; } }; int main() { Test obj; int x = 20; obj.setX(x); obj.print(); return 0; } For constructors, initializer list can also be used when parameter name is same as member’s name. To return reference to the calling object When a reference to a local object is returned, the returned reference can be used to chain function calls on a single object. #include<iostream> using namespace std; class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; } Test &setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y << endl; } }; int main() { Test obj1(5, 5); // Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); obj1.print(); return 0; }output x = 10 y = 20
转载请注明原文地址: https://www.6miu.com/read-34913.html

最新回复(0)