面试例题—sizeof(2)

来源:互联网 发布:网络黄金egd网址多少 编辑:程序博客网 时间:2024/05/23 18:32

例题:what is the output of the following code?

// sizof2.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include<iostream>using namespace std;class A{};class A2{char d,e;};struct B{};struct C{ char b,c;};struct D{int x,y;};int main(int argc, char* argv[]){cout<<sizeof(A)<<endl;cout<<sizeof(A2)<<endl;A *p1 = new A();A *p2;A p3;cout<<sizeof(p1)<<endl;cout<<sizeof(p2)<<endl;cout<<sizeof(p3)<<endl;cout<<sizeof(B)<<endl;cout<<sizeof(C)<<endl;cout<<sizeof(D)<<endl;return 0;}

结果:

1.A是一个空的类,编译器仍然要给它一个空间,所以类A的大小为1

2.A2类中有两个char类型的变量,所以类A2的大小为2

3.p1是指针类型,大小为4

4.p2是指针类型,大小为4

5.p3是一个A类的对象,大小为1

6.B是一个空的结构体,B的大小为1

7.C是一个含有两个char类型变量的结构体,C的大小为2

8.D是一个含有两个int类型变量的结构体,D的大小为4