this指针指向对象的指针。
this执政变量记录每个单独的对象的内存地址。
对象要在属于自己的成员变量身上写下自己的名字,以证明该成员变量是自己的成员,而不是其他对象成员,this变量帮助对象做到这一点,this变量记录每个
对象的内存地址,然后通过间接访问运算符-->访问该对象的成员。
默认情况下this指针是不用写的:编译器会自动在this前面加上变量之前的。
//
// Created by amesty on 16/5/13.
// Copyright © 2016年 travelrely. All rights reserved.
//
#include <stdio.h>
#include <iostream>
using namespace std;
class A
{
private:
int i;
public :
int get() const { return i ;}
void set(int x) {
this-> i = x;
cout<<"this变量保存的内存地址:\t"<<this<<endl;
}
};
int main()
{
A a;
a.set(9);
cout<<"对象a的内存地址:\t"<<&a<<endl;
cout<<a.get()<<endl;
A b;
b.set(999);
cout<<"对象b的内存地址:\t"<<&b<<endl;
cout<<b.get()<<endl;
return 0;
}
this变量保存的内存地址: 0x7fff5fbff968
对象a的内存地址: 0x7fff5fbff968
9
this变量保存的内存地址: 0x7fff5fbff960
对象b的内存地址: 0x7fff5fbff960
999
Program ended with exit code: 0