Home  >  Article  >  Backend Development  >  What does this pointer point to in c++

What does this pointer point to in c++

下次还敢
下次还敢Original
2024-05-09 03:30:24392browse

This pointer points to the instance of the current object in C. Usage includes: accessing member variables: this-> member variable name calling member function: this-> member function name () passing object reference: passed as a parameter to other functions to reference the current object

What does this pointer point to in c++

What does this pointer point to in C

In C, this pointer is a special pointer that always points to An instance of the current object. That is, the this pointer points to the object that calls a member function or accesses a member variable.

Usage

this Pointers are used in the following scenarios:

  • Access member variables: You can use this->member variable name to access the member variables of the current object.
  • Call member function: You can use this->member function name() to call the member function of the current object.
  • Passing object reference: You can pass the this pointer as a parameter to other functions to reference the current object.

Example

The following example illustrates the use of this pointers:

<code class="cpp">class Person {
public:
    string name;

    void printName() {
        cout << "Name: " << this->name << endl;
    }
};

int main() {
    Person bob;
    bob.name = "Bob";
    bob.printName(); // 输出:"Name: Bob"
}</code>

In this example, printName() The function uses the this pointer to access the name member variable and prints it.

Note

  • Only non-static member functions and constructors have this pointers.
  • Static member functions and constructors cannot access the this pointer because they do not belong to any specific object.
  • this The pointer always points to the object of the currently executing function.

The above is the detailed content of What does this pointer point to in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does sum mean in c++Next article:What does sum mean in c++