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

‘this’ pointer in C++

2015-09-09 15:05 369 查看
this指针作为一个隐藏的参数传递给所有的non-static成员函数,作为一个局部变量。是一个const-pointer,指向的是当前对象的地址。在static成员函数中没有this指针,因为static成员变量不能调用对象内的non-static成员。

this指针有两个用途:

(1)返回调用对象的引用。

/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}


(2)当局部变量名称和成员变量名称相同时。

#include<iostream>
using namespace std;

/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

this指针的类型

当类X的成员函数声明为const时,this指针为:const X*
当类X的成员函数声明为volatile时,this指针为:volatile X*
当类X的成员函数声明为const volatile时,this指针为:const volatile X*

#include<iostream>
class X {
void fun() const {
// this is passed as hidden argument to fun().
// Type of this is const X*
}
};
Run on IDE
Code 2

#include<iostream>
class X {
void fun() volatile {
// this is passed as hidden argument to fun().
// Type of this is volatile X*
}
};
Run on IDE
Code 3

#include<iostream>
class X {
void fun() const volatile {
// this is passed as hidden argument to fun().
// Type of this is const volatile X*
}
};


翻译:http://www.geeksforgeeks.org/g-fact-77/

可不可以delete this指针?

可以,但只有当对象是用new创建出来的时候,其成员函数中才可以使用delete this。
class A
{
public:
void fun()
{
delete this;
}
};

int main()
{
/* Following is Valid */
A *ptr = new A;
ptr->fun();
ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr.

/* And following is Invalid: Undefined Behavior */
A a;
a.fun();

getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: