您的位置:首页 > 编程语言 > C语言/C++

C++ 中的this指针

2016-01-21 19:41 405 查看
关于this指针tutorials是这样解释的:

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter
to all member functions. Therefore, inside a member function,
this may be used to refer to the invoking object.

Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.

--> this就是非静态方法中的第0个隐藏参数,值为调用对象的指针。





this指针的含义及其用法:

1. this指针是一个隐含于每一个成员函数中的特殊指针。它指向正在被该成员函数操作的那个对象。

2. 当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,然后调用成员函数,每次成员函数存取数据成员时,由隐含使用this指针。

3. 当一个成员函数被调用时,自动向它传递一个隐含的参数,该参数是一个指向这个成员函数所在的对象的指针。

4. 在C++中,this指针被隐含地声明为: X *const this,这意味着不能给this 指针赋值;

在X类的const成员函数中,this指针的类型为:const X* const, 这说明this指针所指向的这种对象是不可修改的(即不能对这种对象的数据成员进行赋值操作);

5. 由于this并不是一个常规变量,所以,不能取得this的地址。

6. 在以下场景中,经常需要显式引用this指针

(1) 为实现对象的链式引用(如例1);

(2) 为避免对同一对象进行赋值操作(如例2);

(3) 在实现一些数据结构时,如list.



7. 举例:

//例1:

#include <stdio.h>
#include <string.h>

class Person {
public:
typedef enum {
BOY = 0,
GIRL = !BOY
} SexType;
public:
Person(char *n, int a, SexType s)
{
name = new char[strlen(n)+1];  //这里的 name 等价于this->name
strcpy(name,n);                //这里的 name 等价于this->name
age = a;                       //这里的 age 等价于this->age
sex = s;                       //这里的 sex 等价于this->sex
}
int get_age(void) const
{
//age++; //compile error, 因为 age等价于this->age,而 get_age又是一个const成员函数,
//不能对 this指针所指向的这种对象进行修改,这也是const的一个作用。
//这样做的好处是,增加了代码的健壮性。
return age;
}
Person& add_age(int a)
{
age +=a;
return *this; // 返回本对象的引用
}
private:
char *name;
int age;
SexType sex;
};

void TestPerson(void)
{
Person ZhangSan("ZhangSan", 20, Person::BOY);
printf("ZhangSan.age = %d\n", ZhangSan.get_age());
printf("ZhangSan.add_age = %d\n", ZhangSan.add_age(1).get_age()); //增加1岁的同时,可以对新的年龄直接输出;

return;
}

int main(void)
{
TestPerson();
while(1);

}

/* result:
ZhangSan.age = 20
ZhangSan.add_age = 21
*/


//例2:

#include <stdio.h>

class Location {
int X,Y;//默认为私有的
public:
void init(int x,int y) { X =x; Y = y;};
void assign(Location& pointer);
int GetX(){ return X; }
int GetY(){ return Y; }
};

void Location::assign(Location& pointer)
{
if(&pointer!=this) //同一对象之间的赋值没有意义,所以要保证pointer不等于this
{
X=pointer.X;
Y=pointer.Y;
}
}

int main()
{
Location x;
x.init(5,4);

Location y;
y.assign(x);

printf("x.X = %d, x.Y = %d \n",  x.GetX(), x.GetY());
printf("y.X = %d, y.Y = %d ",  y.GetX(), y.GetY());

while(1);
return 0;
}
/* result:
x.X = 5, x.Y = 4
y.X = 5, y.Y = 4
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: