C++中的this指针
C++中类的this指针与python中self用法相似,会在类实例化时自动建立this指针,并指向这个对象的地址,可以通过this访问对象成员(非静态)。
#include<iostream>
#include<cstring>
using namespace std;
class Person {
public:
typedef enum {
BOY = 0,
GIRL
}SexType;
Person(string b, int a, SexType s) {
name = b;
age = a;
sex = s;
}
int get_age() const {
return this->age;
}
Person& add_age(int a) {
age += a;
return *this;
}
~Person() {
}
private:
string name;
int age;
SexType sex;
};
int main() {
std::string s= "zhangsan";
Person p(s, 20, Person::BOY);
cout << p.get_age() << endl; //使用this
cout << p.add_age(10).get_age() << endl; //使用,设置,再获取
return 0;
}
通过断点调试,可以看到this的类型:
总结:
this在成员函数的开始执行前构造,在成员的执行结束后清除。
上述的get_age函数会被解析成get_age(const A * const this),add_age函数会被解析成add_age(A* const this,int a)。
在C++中类和结构是只有一个区别的:类的成员默认是private,而结构是public。this是类的指针,如果换成结构,那this就是结构的指针了。
参考 this那些事