C++中this指针用法详解及实例

2020-01-06 17:10:44丽君

C++中this指针用法详解及实例

概要:

本文简单介绍this指针的基本概念,并通过一个实际例子介绍this指针用于防止变量命名冲突和用于类中层叠式调用的两个用法。

this指针概览

C++中,每个类 对应了一个对象,每个对象指向自己所在内存地址的方式即为使用this指针。在类中,this指针作为一个变量通过编译器隐式传递给非暂存(non-static)成员函数。因为this指针不是对象本身,因此sizeof函数并不能用于确定this指针所对应的对象大小。this指针的具体类型与具体对象的类型以及对象是否被const关键字修饰 有关。例如,在类Employee的非常量函数中,this指针类型为Employee ,若为常量函数,则this指针类型为const Employee 。由于this本身是一个指向对象的指针,因此*this这类去指针操作则得到本类中对象的地址。关于this指针的使用,举例如下:

本文代码引用和免责声明:


/**************************************************************************
 * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and        *
 * Pearson Education, Inc. All Rights Reserved.              *
 *                                    *
 * DISCLAIMER: The authors and publisher of this book have used their   *
 * best efforts in preparing the book. These efforts include the     *
 * development, research, and testing of the theories and programs    *
 * to determine their effectiveness. The authors and publisher make    *
 * no warranty of any kind, expressed or implied, with regard to these  *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or    *
 * consequential damages in connection with, or arising out of, the    *
 * furnishing, performance, or use of these programs.           *
 **************************************************************************/

Test.h文件:


#ifndef TEST_H
#define TEST_H

class Test 
{
public:
  explicit Test( int = 0 ); // default constructor
  void print() const;
private:
  int x;
}; // end class Test

#endif /* TEST_H */


Test.cpp文件:


#include "Test.h"
#include <iostream>
using namespace std;

// constructor
Test::Test( int value ) : x( value ){}

// print x using implicit and explicit this pointers;
// the parentheses around *this are required
void Test::print() const  
{
  // implicitly use the this pointer to access the member x
  cout << "    x = " << x;
  // explicitly use the this pointer and the arrow operator
  // to access the member x
  cout << "n this->x = " << this->x;
  // explicitly use the dereferenced this pointer and 
  // the dot operator to access the member x
  cout << "n(*this).x = " << ( *this ).x << endl;
} // end function print