与sizeof派生类混淆

des*_*ado 1 c++ inheritance sizeof

class base
{
  private:
  int a;
  };
class base2
{
  private:
  int b;
  };
class derived:public base,public base2
{
  private:
  int c;
  };
main()
{
  base b;
  derived d;
  cout<<size of(base)<<size of(base2)<<size of(derived);
}
Run Code Online (Sandbox Code Playgroud)

因为int a和int b是私有变量.所以它们不会在派生类中继承.所以输出应该是4 4 4但它是输出:4 4 12为什么?

das*_*ght 6

因为int a并且int b是私有变量.所以它们不会在derived课堂上继承

那是错的 - 当然它们是继承的,如果没有它们,基类中的代码将无法工作.它只是derived无法找到它们,但它不会改变sizeof派生类.

考虑一下您的示例的扩展:

class base {
private:
    int a;
protected:
    base() : a(123) {}
    void showA() {cout << a << endl;}
};

class base2 {
private:
    int b;
protected:
    base2() : b(321) {}
    void showB() {cout << b << endl;}
};

class derived:public base,public base2 {
private:
    int c;
public:
    derived() : c (987) {}
    void show() {
        showA();
        showB();
        cout << c << endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

即使你的derived类不能读取或更改ab,它可以通过调用相应的功能在其基地展示自己的价值.因此,变量必须留在那里,否则showAshowB成员函数将不能够做好自己的工作.