this指针

2014-11-24 01:32:58 · 作者: · 浏览: 1

this指针
在调用类的成员函数时,隐含了一个this指针。该指针式一个指向正在对某个成员函数操作的对象的指针。
当一个对象调用成员函数时,系统先将改对象的地址赋给this指针,然后调用成员函数。每次成员函数访问对象成员时,则隐含地使用了this指针。
实际中,通常不显示使用this指针引用数据成员和成员函数,需要时还可以使用*this来标识该成员的对象。


[cpp]
#include
using namespace std;
class A
{
public:
A(int i, int j)
{
a = i;
b = j;
}
A()
{
a = b = 0;
}
~A(){ cout << "Destructor!" << endl;} // 调用析构函数
void Copy ( A &aa );
int Returna()
{
return a;
}
int Returnb()
{
return b;
}
private:
int a, b;
};
void A::Copy(A &aa)
{

if ( this == &aa)
return ;
*this = aa;
}
int main()
{
A a1, a2(3, 4);
a1.Copy(a2);
cout << a1.Returna() - a2.Returnb()
<< "," << a1.Returnb() + a2.Returnb()
<< endl;

return 0;
}

#include
using namespace std;
class A
{
public:
A(int i, int j)
{
a = i;
b = j;
}
A()
{
a = b = 0;
}
~A(){ cout << "Destructor!" << endl;} // 调用析构函数
void Copy ( A &aa );
int Returna()
{
return a;
}
int Returnb()
{
return b;
}
private:
int a, b;
};
void A::Copy(A &aa)
{

if ( this == &aa)
return ;
*this = aa;
}
int main()
{
A a1, a2(3, 4);
a1.Copy(a2);
cout << a1.Returna() - a2.Returnb()
<< "," << a1.Returnb() + a2.Returnb()
<< endl;

return 0;
}

\