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指針的類型
#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指針?
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;
}