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
見た目ほど特別なポインターではないことを示しているため、これについて言及しています。この特定のハックは、メンバー変数を作成するよりも優れたソリューションであるmutable
ことがよくありmutable
ます。クラスのメソッド。 const