先来看一段代码:
1 //this指针问题 2012年7月18日0:37:13 2 #include <iostream> 3 using namespace std; 4 5 6 class point 7 { 8 public: 9 10 int x,y; 11 12 point(int a,int b) 13 { 14 x= a; 15 y = b; 16 } 17 18 void input(int x,int y ) 19 { 20 21 22 x= x; 23 y =y; 24 } 25 26 27 void output() 28 { 29 cout<<x<<y; 30 31 } 32 }; 33 34 int main() 35 { 36 37 38 point a(5,5); 39 40 a.input(10,10); 41 a.output(); 42 return 0; 43 44 }
输出的结果是多少呢?
。。。。。
此处省略1000个字
对啦,答案还是5,5
可能有些读者感到疑惑,为什么不是10,10呢
真正的原因是c++变量的作用域问题,函数形参跟你的变量重名,在函数内部,c++会仍然使用函数形参,也就是现在真正的类变量x,y是没有调用到的!
那怎么样才能调用到类变量呢? 对啦
有的读者可能想到这样
void input(int a,int b )
{
x= a;
y =b;
}
的确这是一种解决办法!
回到本文的重点,这个时候我们可以这样:
//this指针问题 2012年7月18日0:37:13 #include <iostream> using namespace std; class point { public: int x,y; point(int a,int b) { x= a; y = b; } void input(int x,int y ) { this->x= x; this->y =y; } void output() { cout<<x<<y; } }; int main() { point a(5,5); a.input(10,10); a.output(); return 0; }
我们使用了this->x = x;这样的写法,那么这个this指针是个什么东西呢!!
原来这样,笔者会不会有这样的疑问,我们的类 point ,比如创建了a,b,c三个对象
均调用函数output,那么我们的类是如何知道,我们是哪个对象调用了这个output函数呢??
原来c++在这块,把一个东西隐藏了,对就是所属对象的地址也就是我们的this指针
我们来看下构造函数这一块对应的汇编代码
12: point(int a,int b) 004015C0 push ebp 004015C1 mov ebp,esp 004015C3 sub esp,44h 004015C6 push ebx 004015C7 push esi 004015C8 push edi 004015C9 push ecx 004015CA lea edi,[ebp-44h] 004015CD mov ecx,11h 004015D2 mov eax,0CCCCCCCCh 004015D7 rep stos dword ptr [edi] 004015D9 pop ecx 004015DA mov dword ptr [ebp-4],ecx 13: { 14: x= a;
可以看到