1
// inheritence experiment

#include"stdafx.h"
#include<iostream> 

using namespace std;

class base
{
private:
    int i;
};

class derived: public base
{
private:
    int j;
};

int main()
{
    cout << endl << sizeof(derived) << endl << sizeof(base);
    derived o1;
    base o2;
    cout << endl << sizeof(o1) << endl << sizeof(o2); 
}

I'm getting this output:

8
4
8
4

why's that so? private data members of a base class aren't inherited into the derived class, so why I am getting 8 bytes for both, the size of derived and o1 ?

4

5 回答 5

9

Private members are inherited. You just cannot access them from your derived class.

于 2012-05-24T18:31:41.727 回答
3

私有成员实际上在派生类中,它们只是在派生类中不可访问。private 关键字是为了防止从基类派生的程序员更改基类设计者不希望您更改的值,因为它可能会改变基类的功能。

在这里查看更深入的解释

脆弱的基类

于 2012-05-24T18:34:51.297 回答
2
class base {
public:
  base(int v) : m_value(v) { }
  int value() { return m_value; }
private:
  int m_value;
};

class derived : private base {
  derived(int v) : base(v) { }
  int value2() { return value(); }
};

int main()
{
  derived d(2);
  return d.value2();
}

如果私有基类没有将值存储在某处,您希望这如何工作?

您对“继承到派生类”一词的选择让我认为您对继承的工作方式感到困惑。基类的成员不会继承或复制派生类中派生类包含基类型的实例,作为完整派生对象中的子对象,因此派生类(通常)至少与其基类的总和一样大。

考虑这段代码:

struct A {
private:
  int i;
};

struct B {
  int j;
};

struct derived : A, B {
  int k;
};

一个A对象在内存中以 的形式排列int,a 也是如此B。一个derived对象可以作为一个对象在内存中布局A,然后是一个B对象,然后是一个int,这意味着它是三个ints 的序列。基类成员是公共的还是私有的都不会影响这一点。

于 2012-05-24T20:36:25.597 回答
1

当然它们是继承的——毕竟,基类的行为可能取决于它们的存在——它们只是不可访问!

于 2012-05-24T18:32:22.940 回答
0

基类的继承方法仍然可以使用私有成员。他们必须在那里。

于 2012-05-24T18:32:19.697 回答