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_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中的調用示例:
#include "Test.h"int main(){ Test testObject( 12 ); // instantiate and initialize testObject testObject.print(); return 0;} // end main
本例中,由于this本身是指針,因此類中變量x的讀寫方式即為this->x。注意由于this變量是隱式傳遞的,因此在同一個類中的成員函數中直接調用x變量其效果等同于通過this指針調用x。使用去指針化的this變量則獲得對象地址,因此通過對象地址調用變量的方式是用點號操作符。
介紹完this指針獲取變量的方式之后,接下來本文將介紹this指針的兩個作用。
一、this指針用于防止類中的變量沖突
this指針可以用來防止數據域與傳入參數變量名相同可能導致的問題。以下列程序為例:
Time.h文件
//此處省略定義頭
class Time {public: //...此處省略若干行非重點部分 Time &setHour( int ); // set hour Time &setMinute( int ); // set minute Time &setSecond( int ); // set second //...此處省略若干行非重點部分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寫法類似
此處代碼傳入參數名為hour,hour被賦值對象也是本類私有變量hour,此時用this指針指向hour變量的方式就防止了命名重復。注意到前述代碼的返回值為指向這個對象的指針,這與接下來本文要分析的第二點有關。
二、this指針用于層疊式調用
通過返回類的去指針化的this指針*this,事實上就是返回了類所在的地址。那么此類就可以被層疊調用。如上述Time這個對象,主程序調用示例如下:
main.cpp文件:
//省略非重要的預處理指令和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其實得到的返回值為&t,那么獲取setMinute的方法就是t.setMinute。同樣運行t.setHour(18).setMinute(30)之后返回值仍為&t,因此可以繼續調用setSecond。
那么,這樣返回指向對象的類安全性有問題么?注意,此處類是以整個對象的形式被返回的,并沒有出現類中的私有成員地址被返回的情況,因此返回對象地址與返回變量的地址本質是不同的。返回對象之后,對象仍然確保了私有變量的封裝性,因此就變量地址造成的安全性問題,此處是不必考慮的。
感謝 閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答