子类的对象存储超类的私有属性

时间:2018-05-24 12:53:03

标签: c++

我正在使用C ++学习面向对象的编程。我试着写下面的代码:

#include <iostream>
using namespace std;
class A
{
private:
  int att_1;
  int att_2;
  int att_3;
public:
  A()
  {
    att_1 = att_2 = att_3 = 0; 
  }
  int sum()
  {
    return att_1+att_2 + att_3;
  }
};
//Class B want to inherits from class A
//Class B also has doSomeThing() method that is not related to A attributes
class B : public A
{
public:
//just a function to show something
  void doSomeThing()
  {
    cout << "I am B object\n";
  }
};
//class C just want to inherits doSomeThing() method from B
//and it also has an attribute that named as d
class C :public B
{
public:
  int att_4;
};
int main()
{
  C obj;
  obj.doSomeThing();
  cout<<sizeof(C); //sizeof(C)=20 bytes
             //sizeof(C)=20 bytes, it includes att_1, att_2, att_3 and att_4
             //but "obj" does not want to use att_1, att_2, att_3
  return 0;
}

正如你所看到的,&#34; obj&#34;只想从B类继承doSomeThing()方法,它不想使用att_1,att_2,att_3但它必须花费 用于存储A类属性的空间(att_1,att_2,att_3)。它浪费了记忆。我想问一下,我们是否被迫接受这种浪费?

0 个答案:

没有答案
相关问题