首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

this 指针是read only吗?该怎么处理

2013-12-15 
this 指针是read only吗?面试宝典的题,怀疑答案写错了选项D.this pointer is not counted for calculating

this 指针是read only吗?
面试宝典的题,怀疑答案写错了
选项D.this pointer is not counted for calculating the size of the object
E.this 指针是read only
答案写的是E是对的,但是解释中证明D对。所以呢?
[解决办法]
1)
this指针和对象无关,不是对象的一部分。

只是在非静态成员函数的调用过程中,隐式传递的一个参数,是调用该函数的那个对象的地址。
在该函数调用过程中 this指针是不可修改的,指针的值,也是不会改变的。

对于成员函数的定义来数,是该函数的隐藏的第一个参数。
实际参数表里的参数,是更后面的参数。

其他地方不存在this指针。
也不是类的成员变量,类中一般没有这个数据。

2)
D,E 只怕都是对的。

3)代码事例:
 

 class A{

  int x;
public :
   int getX()const{  
     //访问函数,隐藏参数 this,是函数的第一个参数; 
     //定义形式为 const A *const this; 
       return this->x;
   } 
   void setX(int val){
     // 修改函数,隐藏参数 this,是函数的第一个参数;
     // 定义形式为 A *const this; 
         this->x =val;
   };
};

int main{
  A a;
  int v=10;
  v = a.getX(); // this == &a;
  a.setX(v);    // this == &a;

  A &r =a; 
  v = r.getX(); // this == &r == &a;
  r.setX(v);    // this == &r == &a;

  A *p = &a;   
  v = p->getX(); // this == p == &a;
  p->setX(v);    // this == p == &a;  
  return 0;     
}

热点排行