1、问题描述
写出代码中sizeof的结果
#include <iostream> #include <complex> using namespace std; class A1 { A1() {} ~A1() {} }; class Base { public: Base () { cout << "base-ctor" << endl; } ~Base () { cout << "base-dtor" << endl; } virtual void f(int) { cout << "Base::f(int)" << endl; } virtual void f(double) { cout << "Base::f(double)" << endl; } }; class Derived: public Base { public: Derived () { cout << "Derived-ctor" << endl; } ~Derived () { cout << "Derived-dtor" << endl; } void f(complex<double>) { cout << "Derived::f(complex)" << endl; } }; int main() { Base b; Derived d; cout << sizeof(A1) << endl; cout << sizeof(Base) << endl; // A. 4 B. 32 C. 20 D. platform-dependent cout << sizeof(Derived) << endl; // A. 4 B. 8 C. 36 D. platform-dependent return 0; }
2、答案
1 4 4
3、析
1)无虚函数且无数据成员,类的sizeof大小为1
2)有虚函数且无数据成员,类的sizeof大小为4,有虚函数类内有指针