#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;
}
为什么在这种情况下sizeof
函数返回4?从我的立场出发,指针
ob
指向派生类d
的大小为20的已创建对象xyz
。因此sizeof(*ob)
也应返回以下值:20。 最佳答案
sizeof
运算符处理静态类型,而不处理动态类型。 *ob
是静态类型abc
,因此它是返回的大小。
注意sizeof
在编译时执行,并且编译器无法找出属于继承层次结构的实例的动态类型。在您的代码段中,看起来这种查找很容易执行,但可以想象
abc *ob;
sizeof(*ob);
其他翻译单元中甚至不知道xyz
的任何地方。