0

インスタンス変数が継承されている場合、サブクラスで変更してもスーパークラスの値には影響しません。逆も同様です。これは、2 つのインスタンス変数があることを意味します。しかし、私が行うsizeof( sublcass )と、インスタンス変数は 1 つだけがサイズに含まれます。スーパークラス用に作成される 2 番目のオブジェクトはありますか?

ここに私が言っていることを説明するための小さなスニペットがあります:

struct Super {

  int x;

  void func() {

    cout << "SUPERCLASS" << endl;
    cout << x << endl;            /* prints garbage value */
    x = 4;                        
    cout << x << endl;            /* prints 4 */

  }

};

struct Sub : public Super {


  void func() {

    x = 10;
    Super b;
    b.func();
    cout << "SUB" << endl;
    cout << x << endl;       /* prints 10 */

  }

};



int main() {

  Sub b;
  b.func();

  return 0;

}

出力:

SIZE: 4
SUPERCLASS
2867344
4
SUB
10
4

2 に答える 2

0

この関数では、 type の新しいオブジェクトを作成してSuper出力します。

void func() {

    x = 10;

    // b is now a totally different (and unrelated object)
    // so calling b.func() will print the x variable that
    // is valid for that instance (not this instance)
    Super b;
    b.func();

    cout << "SUB" << endl;
    cout << x << endl;       /* prints 10 */

  }

あなたの仮定は実際には間違っています. class 内に存在するインスタンス変数は1つだけです. 関数が非表示になっているため、呼び出すには、スコープ解決演算子 ( ) を使用して直接呼び出す必要があります。xSubSub::func()Super::func()::

void func() {

    // this is the one (and only) x that is in scope
    // inherited by `Sub` from `Super`.
    x = 10;

    // call Super::func(), using the scope resolution operator
    Super::func();

    cout << "SUB" << endl;
    cout << x << endl;       /* prints 10 */

  }
于 2013-10-17T17:33:06.600 に答える