本帖最后由 baizy77 于 2018-10-1 20:50 编辑
版权声明 --------------------------------------------------------------------------------------------------------------------- 作者: 女儿叫老白 (白振勇) 转载请注明出处! --------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------
引言 --------------------------------------------------------------------------- 说到this指针,大家可能既陌生又熟悉,那么this指针到底是干啥用的,使用时又要注意些什么呢?
正文 --------------------------------------------------------------------------- 在C++中提供了this指针来访问对象自身。那么,在开发的时候我们一般会在什么情况下会用到this指针呢? 一种情况是在调试的时候,比如在调试一个堆栈的时候。如果当前堆栈处于某一个类的接口内部,那么我们就可以通过打印或者查看this指针的值来确定当前对象的地址,进而判断其是否合法。比如: void CMyClass::getValue() { // 如果堆栈执行到该接口内部,那么我们就可以在该接口内部打印this指针。 // 在visualstudio 的 IDE环境中可以添加监视。 // 在gdb的堆栈调试中,可以直接打印:print this } 第二种情况是赋值构造函数中,比如下列函数的最后一句代码: CMYClass& operator=(const CMYClass & right) { if (this != &right) { xxx =right.getxxx(); yyy = right.getyyy(); } return *this; } 再就是类的const成员函数调用非const成员函数时,编译器会报错。比如: //@ myclass.h class CMyClass { …… public: int getValue() const; int calculateValue() { m_nValue ++;} private: int m_nValue; }; //@ myclass.cpp int CMyClass::getValue() const { return calculateValue(); } 如果按照上面的代码进行编程,编译器会报错: 有两种方式消除编译错误: 1. 将getValue()的const限定符去掉。 2. 将getValue()改为: int getValue(){return m_nValue;} 然后由调用者自行调用calculateValue()和getValue()。
|