面试题:const、static、sizeof

#include <iostream>
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<<a.f();
    return 0;
}

const自不必多少,可以定义常量、修饰函数参数、修饰函数返回值等,c++中还可以修饰函数的定义体,定义类中某成员函数为恒态函数

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

2、sizeof和static

1、sizeof

#include <iostream>
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 <iostream>
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 <iostream>
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字节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值