面试题:const、static、sizeof

2014-11-24 09:43:19 · 作者: · 浏览: 0

#include 
  
   
using namespace std;

class A{
public:
	mutable int m;
	
	int f()const{
		return ++m;
	}
	A(int i):m(i){}
};

int main(){
	A a(0);
	cout<
   
    
const自不必多少,可以定义常量、修饰函数参数、修饰函数返回值等,c++中还可以修饰函数的定义体,定义类中某成员函数为恒态函数

这里介绍下我们忽略掉的mutable,mutable就是为了突破const限制而设置的

2、sizeof和static

1、sizeof

#include 
     
      
using namespace std;

class A{
	bool a;
	int b;
	bool c;
};
class B{
	int a;
	bool b;
	bool c;
};
int main(){
	printf("%d\n",sizeof(A));
	printf("%d\n",sizeof(B));
    return 0;
}
     

输出结果为12和8,为什么不同?

这是因为编译器进行了数据对齐处理

对于A:

|bool|----|----|----|

|----------int-------|

|bool|----|----|----|

对于B:

|----------int---------|

|bool|bool|----|----|

所以A占12字节,B占8字节

2、static

#include 
     
      
using namespace std;

class A{
	int a;
	static int b;
};
class B{
	int a;
	char b;
};
class C{
	float a;
	char b;
};
class D{
	float a;
	int b;
	char c;
};
class E{
	double a;
	float b;
	int c;
	char d;
};
int main(){
	printf("%d\n",sizeof(A));//4
	printf("%d\n",sizeof(B));//8
	printf("%d\n",sizeof(C));//8
	printf("%d\n",sizeof(D));//12
	printf("%d\n",sizeof(E));//24
    return 0;
}
     

static存放在全局数据区,sizeof计算栈中分配的大小,所以是4

对于E:因为double长度为8字节,对齐模数(在windows中就是其长度)为8,所以大小为8的整数倍

|----|----|----|----|----|----|----|----|

|----float--------|--------int--------|

|--char-|----|----|----|----|----|----|

为24字节

3、

#include 
     
      
using namespace std;

class A{
	int a;
	static int b;
	virtual void f(){};
	virtual void f2(){};
	void g(){}
};
class B{

};
class C:public B{

};
int main(){
	printf("%d\n",sizeof(A));//8
	printf("%d\n",sizeof(B));//1
	printf("%d\n",sizeof(C));//1
    return 0;
}
     

对于A:输出为8,包含int a的4字节和虚表指针的4字节,成员函数不占空间

B:空类需占1字节

C:继承类空类也需占1字节