C++中類的sizeof

小弟季義欽發表於2012-11-01
#include <iostream>
using namespace std;

#pragma pack(2)  
class A{  
    int i;		//4
    union U{	//14
        char buff[13];  
        int i;  
    }u;	//注意,這裡是申明瞭一個union變數
    enum{red, green, blue} color;	//4 

	void foo() {}					//0  
    typedef char* (*f)(void*);		//0  
	int g(){int i;}					//0
};

class B{
	B(){}			//0
	virtual g(){}	//4
	virtual f(){}	//所有虛擬函式放在一張虛表中,指向虛表的指標的4位元組
};

class C{};

int main(){
	cout<<sizeof(A)<<endl;	//8
	cout<<sizeof(B)<<endl;	//4
	cout<<sizeof(C)<<endl;	//1
	return 0;
}


再看一個:

#include <iostream>

using namespace std;
class A {  
public:  
    int b;  
    char c;  //注意地址對齊
    virtual void print(){  
        cout<<"this is father's function!"<<endl;  
    }  
};  
  
class B : A {  
public:  
    virtual void print(){  
        cout<<"this is children's function!"<<endl;  
    }  
};  
int main(void){  
    cout<<sizeof(A)<<","<<sizeof(A)<<endl; //12,12      
    return 0;  
}

相關文章