だけthis
についてのいくつかのランダムな事実は、他の回答を補完します
class Foo {
public:
Foo * foo() { return this; }
const Foo * cfoo() const { return this; /* return foo(); is an error */ }
};
Foo x; // can call either x.foo() or x.cfoo()
const Foo y; // can only call x.cfoo()
オブジェクトがconst
で、this
の種類はconst
へのポインタになります。
class Bar {
int x;
int y;
public:
Bar() : x(1), y(2) {}
void bar (int x = 3) {
int y = 4;
std::cout << "x: " << x << std::endl;
std::cout << "this->x: " << this->x << std::endl;
std::cout << "y: " << y << std::endl;
std::cout << "this->y: " << this->y << std::endl;
}
};
this
ポインタは、関数パラメータまたはローカル変数の陰に隠れたメンバにアクセスするために使用することができます。
template <unsigned V>
class Foo {
unsigned v;
public:
Foo() : v(V) { std::cout << "<" << v << ">" << " this: " << this << std::endl; }
};
class Bar : public Foo<1>, public Foo<2>, public Foo<3> {
public:
Bar() { std::cout << "Bar this: " << this << std::endl; }
};
多重継承は異なる親が異なるthis
値を持つことになります。最初に継承された親だけが派生オブジェクトと同じthis
値を持ちます。
出典
2013-05-11 01:33:08
jxh
すべての非静的メソッドには暗黙の 'this'ポインタがあります。典型的なC++実装では、最初の整数引数スロットに渡されます。 –
私はこのようなことを避けるでしょう - "fooに何かをする"関数はおそらくFooのメンバ関数/メソッドでなければなりません! –
@Wayne Uroda:必ずしもそうではありません。 –