本文共 2528 字,大约阅读时间需要 8 分钟。
目录
C++中的this指针,在所有非静态成员函数的调用中做为一个隐藏参数进行传递,并且在函数体中可以做为一个局部变量使用。
this是一个const指针,保存当前对象的内存地址。 this指针在静态成员函数中不能使用,因为静态成员函数不需要使用任何对象进行调用。 对于class X, this指针的类型相当于X* const。 同理,如果X的一个成员函数声明为const,则this指针相当于const X *const。下面这些例子显示了this指针的各个使用场景。
当局部变量名称与成员变量名称相同时
#include//case:局部变量x(在setX函数中),与成员变量x相同class Test{private: int x;public: void setX(int x) { //this指针用来接收被局部变量x隐藏了的成员变量x. this->x = x; } void print() { std::cout << "x = " << x << std::endl; }};int main(){ Test obj; int x = 22; obj.setX(x); obj.print(); return 0;}
输出:
x = 22如果是对于构造函数,当参数名称与成员名称相同时,则也可以使用初始化列表来解决这个问题。
做为函数的返回值,返回正在被调用对象的引用。
Test& Test::func (){ // Some processing return *this;}
当一个局部对象返回引用时,返回的引用可以做为一个对象调用下一个函数。这就是chain function calls--链式函数调用。
如下面例子所示:#includeclass Test{private: int x; int y;public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; } Test &setY(int b) { y = b; return *this; } void print() { std::cout << "x = " << x << " y = " << y << std::endl; }};int main(){ Test obj1(5, 5); // Chained function calls. obj1.setX(11).setY(22); obj1.print(); return 0;}
输出:
x = 11 y = 22this指针是const指针,不能被赋值。
#includeusing namespace std;class Test{private: int x;public: Test(int x = 0) { this->x = x; } void change(Test *t) { this = t; } void print() { cout << "x = " << x << endl; }};int main(){ Test obj(5); Test *ptr = new Test (10); obj.change(ptr); obj.print(); return 0;}
编译失败。提示错误:
In member function `void Test::change(Test*)': non-lvalue in assignment删除这一行后,运行输出:
x = 5这个在本人之前的,也有过说明。
#includeusing namespace std;class Test{private: int x; int y;public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } static void fun1() { cout << "Inside fun1()"; } static void fun2() { cout << "Inside fun2()"; this->fun1(); }};int main(){ Test obj; obj.fun2(); return 0;}
编译失败。提示:
In static member function `static void Test::fun2()': `this' is unavailable for static member functions去掉这一行,运行输出:
Inside fun2()、显式delete this,可能导致内存异常
#includeusing namespace std;class Test{private: int x; int y;public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } void setX(int a) { x = a; } void setY(int b) { y = b; } void destroy() { delete this; } void print() { cout << "x = " << x << " y = " << y << endl; }};int main(){ Test obj; obj.destroy(); obj.print(); return 0;}
编译正常,但程序运行时发生异常。
转载地址:http://dqeji.baihongyu.com/