创建子类对象时, 是为超类创建的第二个对象

When a subclass object is created, is a second object created for the Superclass?

本文关键字:创建 对象 超类 第二个 子类      更新时间:2023-10-16

当一个实例变量被继承时,在子类中更改它不会影响它在超类中的值,反之亦然。这意味着有两个实例变量。但是当我做sizeof( sublcass )时,大小中只考虑了一个实例变量。那么有没有为超类创建的第二个对象?

这里有一个小片段来说明我在说什么:

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

在此函数中,创建一个类型为 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 */
  }

您的假设实际上是不正确的,只有一个实例变量x存在于您的类Sub中。 你的函数Sub::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 */
  }

如果您只是明确使用数据成员,您应该看到问题所在:

   void func() {
    this->x = 10;
    Super b;
    b.func();
    cout << "SUB" << endl;
    cout << this->x << endl;       /* prints 10 */
  }

由于this显然不等于&b因此您应该清楚地看到您正在访问不同对象的成员。