国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C++ > 正文

C++中this指針用法詳解及實(shí)例

2020-01-26 14:11:41
字體:
供稿:網(wǎng)友

C++中this指針用法詳解及實(shí)例

概要:

本文簡(jiǎn)單介紹this指針的基本概念,并通過一個(gè)實(shí)際例子介紹this指針用于防止變量命名沖突和用于類中層疊式調(diào)用的兩個(gè)用法。

this指針概覽

C++中,每個(gè)類 對(duì)應(yīng)了一個(gè)對(duì)象,每個(gè)對(duì)象指向自己所在內(nèi)存地址的方式即為使用this指針。在類中,this指針作為一個(gè)變量通過編譯器隱式傳遞給非暫存(non-static)成員函數(shù)。因?yàn)閠his指針不是對(duì)象本身,因此sizeof函數(shù)并不能用于確定this指針?biāo)鶎?duì)應(yīng)的對(duì)象大小。this指針的具體類型與具體對(duì)象的類型以及對(duì)象是否被const關(guān)鍵字修飾 有關(guān)。例如,在類Employee的非常量函數(shù)中,this指針類型為Employee ,若為常量函數(shù),則this指針類型為const Employee 。由于this本身是一個(gè)指向?qū)ο蟮闹羔槪虼?this這類去指針操作則得到本類中對(duì)象的地址。關(guān)于this指針的使用,舉例如下:

本文代碼引用和免責(zé)聲明:

/************************************************************************** * (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_Hclass 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;// constructorTest::Test( int value ) : x( value ){}// print x using implicit and explicit this pointers;// the parentheses around *this are requiredvoid 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

main.cpp中的調(diào)用示例:

#include "Test.h"int main(){  Test testObject( 12 ); // instantiate and initialize testObject  testObject.print();  return 0;} // end main

本例中,由于this本身是指針,因此類中變量x的讀寫方式即為this->x。注意由于this變量是隱式傳遞的,因此在同一個(gè)類中的成員函數(shù)中直接調(diào)用x變量其效果等同于通過this指針調(diào)用x。使用去指針化的this變量則獲得對(duì)象地址,因此通過對(duì)象地址調(diào)用變量的方式是用點(diǎn)號(hào)操作符。

介紹完this指針獲取變量的方式之后,接下來本文將介紹this指針的兩個(gè)作用。

一、this指針用于防止類中的變量沖突

this指針可以用來防止數(shù)據(jù)域與傳入?yún)?shù)變量名相同可能導(dǎo)致的問題。以下列程序?yàn)槔?/p>

Time.h文件

//此處省略定義頭

class Time {public:  //...此處省略若干行非重點(diǎn)部分  Time &setHour( int ); // set hour  Time &setMinute( int ); // set minute  Time &setSecond( int ); // set second  //...此處省略若干行非重點(diǎn)部分private:  unsigned int hour; // 0 - 23 (24-hour clock format)  unsigned int minute; // 0 - 59  unsigned int second; // 0 - 59}; // end class Time

Time.cpp文件:

// set hour valueTime &Time::setHour( int hour ) // note Time & return{  if ( hour >= 0 && hour < 24 )   this->hour = hour;  else   throw invalid_argument( "hour must be 0-23" );  return *this; // enables cascading} // end function setHour// set minute 和 set second寫法類似

此處代碼傳入?yún)?shù)名為hour,hour被賦值對(duì)象也是本類私有變量hour,此時(shí)用this指針指向hour變量的方式就防止了命名重復(fù)。注意到前述代碼的返回值為指向這個(gè)對(duì)象的指針,這與接下來本文要分析的第二點(diǎn)有關(guān)。

二、this指針用于層疊式調(diào)用

通過返回類的去指針化的this指針*this,事實(shí)上就是返回了類所在的地址。那么此類就可以被層疊調(diào)用。如上述Time這個(gè)對(duì)象,主程序調(diào)用示例如下:

main.cpp文件:

//省略非重要的預(yù)處理指令和using命令#include "Time.h" // Time class definitionint main(){  Time t; // create Time object  // cascaded function calls  t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );  //省略其余非重要部分} // end main

此處t.setHour其實(shí)得到的返回值為&t,那么獲取setMinute的方法就是t.setMinute。同樣運(yùn)行t.setHour(18).setMinute(30)之后返回值仍為&t,因此可以繼續(xù)調(diào)用setSecond。

那么,這樣返回指向?qū)ο蟮念惏踩杂袉栴}么?注意,此處類是以整個(gè)對(duì)象的形式被返回的,并沒有出現(xiàn)類中的私有成員地址被返回的情況,因此返回對(duì)象地址與返回變量的地址本質(zhì)是不同的。返回對(duì)象之后,對(duì)象仍然確保了私有變量的封裝性,因此就變量地址造成的安全性問題,此處是不必考慮的。

感謝 閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 邛崃市| 河曲县| 南平市| 汝南县| 简阳市| 弥勒县| 车致| 兴义市| 富裕县| 泽州县| 灵台县| 德阳市| 额济纳旗| 卢氏县| 嘉祥县| 盐城市| 碌曲县| 山丹县| 江陵县| 含山县| 邓州市| 昔阳县| 瑞昌市| 湘乡市| 岐山县| 平陆县| 普安县| 林西县| 布拖县| 福贡县| 古交市| 开江县| 扎赉特旗| 黄大仙区| 新邵县| 合肥市| 东明县| 武鸣县| 萨嘎县| 平乐县| 岑溪市|