‘this’ pointer in C++
2015-09-09 15:05
369 查看
this指针作为一个隐藏的参数传递给所有的non-static成员函数,作为一个局部变量。是一个const-pointer,指向的是当前对象的地址。在static成员函数中没有this指针,因为static成员变量不能调用对象内的non-static成员。
this指针有两个用途:
(1)返回调用对象的引用。
(2)当局部变量名称和成员变量名称相同时。
当类X的成员函数声明为volatile时,this指针为:volatile X*
当类X的成员函数声明为const volatile时,this指针为:const volatile X*
翻译:http://www.geeksforgeeks.org/g-fact-77/
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; }
相关文章推荐
- [C++11 并发编程] 17 超时等待 - clock和duration
- C++在本地路径下创建一个文件
- 【C++11】final, override,重载,重写覆盖,重写隐藏
- 【C++专题】static_cast, dynamic_cast, const_cast探讨
- C++构造函数的继承
- 深入浅出UML类图二
- C++类
- 计算一个整数有多少个1的函数
- Java 的 interface、abstract class 与 C++ 的多继承、虚基类
- c++ 副本构造器
- 深入浅出UML类图一
- C++——运算符重载(三)
- C++中智能指针的设计和使用
- [iOS开发]C语言-04-程序循环结构(while{})视频解说
- C++中头文件(.h)和源文件(.cpp)都应该写些什么
- [iOS开发]C语言-03-程序分支结构(switch)视频解说
- 学习C++后感
- C++默认参数详细解析
- C/C++中算法运行时间的三种计算方式
- C++用法的学习心得