c++ this 指针

来源:互联网 发布:央视网络春晚策划方案 编辑:程序博客网 时间:2024/06/06 20:50


有关this的说明具体见《c++ Primer》

1、说明:类的成员函数具有一个附加的隐含形参,即指向该类对象的一个指针。隐含形参命名为this,与调用成员函数的对象绑定在一起。成员函数不能定义this形参,而是由编译器隐含定义的。成员函数的函数体可以显示的使用this指针(访问数据成员),但是一般不必这么做。编译器在编译的时候会自动加上this指针,比如:object.printfInfo(int a);相当于object.printfInfo(&objectm,int a);  这里的&object就是通过this指针引用的。


2、注意:由于this是对象所有,对于静态成员(成员函数和成员数据),是不存在this指针的。


3、使用场景:this指针主要用于返回对整个对象的引用,比如拷贝构造函数(还有比如对于某些类希望提供连续操作,如myScreen.move(4,0).set(“#”);移动光标然后设置显示字符等),需要返回整个对象的引用,就需要用到this指针。在成员函数中使用this指针返回对调用该函数的对象的引用。还有一种情况需要用到this指针,就是如果类的成员函数的形参命名和类的数据成员命名一样的时候,必须用this指针对类的成员数据赋值,这是由作用域决定的,在类的成员函数内部,形参(局部变量)作用域覆盖了类的成员变量的作用域。


4、this的生命周期

this指针在对象开始执行成员函数之前构造,在成员函数执行结束清除


5、 *this

 *this含义:this就是一个指针,所以可以通过*this进行解引用来访问this指向的对象



#include <iostream>using namespace std; class Screen{public:   Screen& move(int r,int c);     Screen& set(char x);  private:   int r,c;}; Screen& Screen::move(int r,int c){   this->r=r;   this->c=c;   //do sth   return *this;} Screen& Screen::set(char x){   //do sth   return *this;} int main(){   Screen scr=Screen();   scr.move(1,4);   scr.set('a');     scr.move(2,4).set('a');         return 0;}

6、thisconst

具体可以见const的用法

#include <iostream>using namespace std; class Screen{public:   Screen();    Screen& move(int r);        //移动   Screen& set(char x);         //设置    const Screen& display() const;   //const的display   Screen& display();            //非const的display   private:   int r;                  //索引位置   char contents[100];    //内容}; Screen::Screen(){   for(int i=0;i<100;i++)            contents[i]='/0';} Screen& Screen::move(int r){//         this->r=r;    return *this;} Screen& Screen::set(char x){   //do sth   contents[r]=x;   return *this;} const Screen& Screen::display() const{//         r=9;   cout<<"const display called"<<endl;   return *this;} Screen& Screen::display(){   //do sth   cout<<"none const display called"<<endl;   return *this;}    int main(){   Screen scr=Screen();   scr.display();  //right:调用非const的display   scr.move(3);    //right    scr.display().move(4);    //right:调用非const的display   const Screen test=Screen();   test.display();     //right:调用const的display    return 0;}




原创粉丝点击