this in C++

1. What is this?

1. Defined
      in C++, each object can access its own address (pointing to itself) through this pointer. The this pointer is an implicit parameter of all member functions. Therefore, inside a member function, it can be used to point to the calling object.

2. The scope of this is inside the class and can only be used in member functions, and only defined in member functions
    . After creating an object, the this pointer cannot be used through the object. It is also impossible to know the location of the this pointer of an object (the location of the this pointer is only available in member functions). Of course, in member functions, you can know the position of this pointer (you can get it with &this), and you can also use it directly.

3. This pointer cannot be used in static functions, this pointer does not occupy the memory of the class.
4. The friend function does not have this pointer, because the friend is not a member of the class. Only member functions have this pointer.
5. Usage:
    In C++, when a variable in a member function has the same name as a member variable , use the this keyword to represent the member variable.

#include <iostream>
using namespace std;
 
class Student{
    
    
public:
    void setname(char *name);
    void setage(int age);
    void setscore(float score);
    void show();
private:
    char *name;
    int age;
    float score;
};
 
void Student::setname(char *name){
    
    
    this->name = name;
}
void Student::setage(int age){
    
    
    this->age = age;
}
void Student::setscore(float score){
    
    
    this->score = score;
}
void Student::show(){
    
    
    cout<<this->name<<"的年龄是"<<this->age<<",成绩是"<<this->score<<endl;
}
 
int main(){
    
    
    Student *pstu = new Student;
    pstu -> setname("李华");
    pstu -> setage(16);
    pstu -> setscore(96.5);
    pstu -> show();
 
    return 0;
}

This means that the member variables name, age, and score of this object are assigned values ​​by the parameters of the three functions.

Guess you like

Origin blog.csdn.net/Algabeno/article/details/123603082
C++
Recommended