c++ - 与 sizeof 派生类混淆

标签 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);
}

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

最佳答案

since int a and int b are private variables.so they are not getting inherited in derived class

这是错误的——它们当然会被继承,没有它们,基类中的代码将无法工作。只是 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 类无法读取或更改 ab,它也可以通过调用其基类中的相应函数来显示它们的值.因此,变量必须保留在那里,否则 showAshowB 成员函数将无法完成它们的工作。

关于c++ - 与 sizeof 派生类混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195387/

相关文章:

c - sizeof 是否返回 C 中某种类型的字节数或八位字节数?

c - 查找结构的大小

c++ - boost::asio async_send 错误

c++ - 有两个线程的运行时间与一个线程的运行时间没有改善

c++ - 为什么不调用复制构造函数?

c# - 在程序启动时实例化一个随机类

c++ - 在基类构造函数中使用 `this` 是否有效?

无法确定为什么 sizeof 显示不同的值

c++ - 如何填充非线性树

c# - C# 是否为未使用的模板参数生成具体实现?