本節繼續上一次的關於sizeof的講解:
這次主要是探討一下,關於sizeof對於類以及對象之間的內存的大小的關係
二維指針域數組的關係
#include <stdio.h>
int main()
{
//存儲的是指針所以是3*4*4=48
int ** a[3][4];
printf("%d\n",sizeof(a));//48
char** b[3][4];
printf("%d\n",sizeof(b));//48
return 0;
}
空類的大小,以及帶有虛函數的空類的大小
#include <stdio.h>
#include <iostream>
using namespace std;
class A
{
};
class B
{
public:
virtual void f() {}
};
int main()
{
A a;
cout << sizeof(a) << endl;//1
B b;
cout << sizeof(b) << endl;//4
return 0;
}
再來討論一下,帶有類的成員函數以及繼承類對象的大小
#include <stdio.h>
#include <iostream>
#include <complex>
using namespace std;
class Base
{
public:
Base() { cout << "Base Constructor !" << endl; }
~Base() { cout << "Base Destructor !" << endl; }
virtual void f(int ) { cout << "Base::f(int)" << endl; }
virtual void f(double) { cout << "Base::f(double)" << endl; }
virtual void g(int i=10) { cout << "Base::g()" << i << endl; }
void g2(int i=10) { cout << "Base::g2()" << i << endl; }
};
class Derived:public Base
{
public:
Derived() { cout << "Derived Constructor !" << endl; }
~Derived() { cout << "Derived Destructor !" << endl; }
void f(complex<double>) { cout << "Derived::f(complex)" << endl; }
virtual void g(int i=20) { cout << "Derived::g()" << i << endl; }
};
int main()
{
Base c;
Derived d;
Base* pb = new Derived;
cout << sizeof(Base) << endl;//4
cout << sizeof(Derived) << endl;//4
cout << sizeof(pb) << endl;//4
cout << sizeof(c) << endl;//4
cout << sizeof(d) << endl;//4
return 0;
}