1
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);
}

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

4

2 回答 2

6

因为int aint 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;
    }
};

即使您的derived类无法读取或更改aand b,它也可以通过调用其基类中的相应函数来显示它们的值。因此,变量必须保留在那里,否则showAshowB成员函数将无法完成它们的工作。

于 2013-10-05T07:56:15.130 回答
0

private:protected:public:成员字段上的注释仅影响可见性。但是这些字段仍在类中。

花几天时间阅读一本好的 C++ 编程书籍。

于 2013-10-05T07:56:05.387 回答