您可以将this指针视为函数的隐式参数。想象一个像这样的小课
class C {
public:
C( int x ) : m_x( x ) { }
void increment( int value ) {
m_x += value; // same as 'this->m_x += value'
}
int multiply( int times ) const {
return m_x * times; // same as 'return this->m_x * times;'
}
private:
int m_x;
};
它允许您编写类似的代码
C two( 2 );
two.increment( 2 );
int result = two.multiply( 3 );
现在,实际发生的是成员函数increment和multiply使用额外的指针参数调用,指向调用函数的对象。这个指针被称为this方法内部。指针的类型this是不同的,这取决于方法是const(原样multiply)还是不是(与 的情况一样increment)。
你也可以自己做类似的事情,考虑:
class C {
public:
C( int x ) : m_x( x ) { }
void increment( C * const that, int value ) {
that->m_x += value;
}
int multiply( C const * const that, int times ) const {
return that->m_x * times;
}
private:
int m_x;
};
你可以写这样的代码
C two( 2 );
two.increment( &two, 2 );
int result = two.multiply( &two, 3 );
请注意,this指针的类型是C const * const针对multiply函数的,因此指针本身也是指向const的对象!这就是为什么您不能更改const方法内的成员变量的原因 -this指针具有禁止它的类型。这可以使用mutable关键字来解决(我不想走得太远,所以我宁愿不解释它是如何工作的),甚至可以使用const_cast:
int C::multiply( int times ) const {
C * const that = const_cast<C * const>( this );
that->m_x = 0; // evil! Can modify member variable because const'ness was casted away
// ..
}
我之所以提到这一点,是因为它表明它this并不像看起来那样特殊,而且这种特殊的 hack 通常是比制作成员变量更好的解决方案,mutable因为这种 hack 对于一个函数是本地的,而使变量对所有人都是mutable可变的类的方法。 const