引用派生类时基类的对象大小

sou*_*dar 1 c++ size sizeof c++11 c++14

#include<bits/stdc++.h>

using namespace std;

class abc {
  public:
    int a = 45;
  void sum() {
    int s = 55;
    cout << s + a << endl;
  }
};
class xyz: public abc {
  public: int b = 45;
  int c = 54;
  int d = 96;
  int x = 8;
  void show() {
    cout << "xyz class" << endl;
  }
};
int main() {
  abc * ob;
  xyz d;
  ob = & d;
  cout << sizeof( * ob) << endl;
}
Run Code Online (Sandbox Code Playgroud)

为什么sizeof在这种情况下函数返回 4?从我的立场来看,指针ob指向一个已经创建d的派生类对象,xyz其大小为 20。所以sizeof(*ob)也应该返回这个值:20。

lub*_*bgr 6

sizeof运营商与静态类型,而不是动态的交易。*ob是静态类型abc,所以这就是它返回的大小。

请注意,这sizeof是在编译时执行的,编译器无法确定作为继承层次结构一部分的实例的动态类型。在您的代码段中,看起来这种查找可以轻松执行,但请想象一下

abc *ob;

sizeof(*ob);
Run Code Online (Sandbox Code Playgroud)

在其他一些翻译单元中的任何地方,xyz甚至都不知道。

  • 你的意思是“abc* ob;”? (2认同)