1

これを仮定すると:

struct A {
    int a;
    int b;
};

struct B {
    int a;
    int b;

    int func() {
        return this->a + this->b;
    }
};

のインスタンスにBは へのポインタが含まれますfuncか?

この質問をコードで説明するには:

A a; // first 4 bytes are for `int a`, second 4 bytes are for `int b`
B b: // ditto, but is there an extra word for a pointer to function `func`?
4

2 に答える 2

4

いいえ。abはまったく同じサイズです (bへのポインタは格納されませんfunc)。

C++ のクラス関数は、オブジェクト自体からリンク (ポイント) されるのではなく、単に他の関数として格納されます。クラス関数を呼び出すときは、通常の関数を呼び出しているだけです (ポインターから呼び出しているわけではありません)。これがb.func = another_func;、C++ で次のようなことを行うことが違法である理由です。

これをコードで説明するには:

/////////
// C++
/////////
struct B {
    int a;
    int b;

    int func() {
        return this->a + this->b;
    }
};

B b;
b.func();


//////////////////////////////
// Example compile output if it was compiled to C (not actual compile output!)
// i.e. this C code will do the equivalent of the C++ code above
//////////////////////////////
struct B {
    int a;
    int b;
};

int B_func(struct B* this) {
    return this->a + this->b;
}

B b;
B_func(&b);

// This should illustrate why it is impossible to do this in C++:
// b.func = another_func;
于 2013-09-17T02:09:15.500 に答える
0

C++ 関数は、(潜在的に) オブジェクトへの隠しポインタを最初のパラメータとして取る単なる関数です。一意性は、名前マングリングによって達成されます。

関数が仮想でない限り。1 つ以上の仮想関数を持つクラスには「仮想関数テーブル」(vtable) があり、これらのクラスのインスタンスにはインスタンス固有の vtable へのポインターのオーバーヘッドがあります。vtable がオブジェクトの前か後かは、コンパイラ/実装によって異なります。

于 2013-09-17T03:24:26.677 に答える