c++中类中占用字节情况

#include <iostream>
using namespace std;
class A {
private:
	int a1;
public:
	virtual void func1() {}
	
};
class B : public A {
private:
	int b;
public:
	virtual void func1() {}
	virtual void func2() {}
};
class C {


};
int main() {
	cout << "The size of class A is " << sizeof(A) << endl;
	cout << "The size of class B is " << sizeof(B) << endl;
	cout << "The size of class B is " << sizeof(C) << endl;
	
	
	return 0;
}

在这里插入图片描述
对象的大小是它的数据成员所占存储空间之和,就和结构体一样。类中的函数是所有该类对象通用的方法,不算作对象的成员,因此也不算在对象的存储空间内

问题:类里面不管有多少个函数,这个类的对象只占1个字节的内存。这个字节的内存的内容是什么?是指针吗?指针不是占4个字节吗?

当类中类有定义任何变量的时候,类的对象都是1个字节的,当类中没有任何变量的时候,这个类里没有任何真正的成员变量,所以大小应该是0,但0大小不好在内存中定位一个地址,所以,就规定它大小为0的对象要占一字节空间,以便让它拥有一个合法的地址。如果是有派生类的,还有考虑到内存对齐的问题的。
A中virtual 相当于指向虚函数表的指针;所以virtual 占用四个字节 加上int 的四个字节相当于8个字节。
B 中1一个int 两个virtual 所以有12个字节public继承是不会继承A中占用的字节数
virtual public 继承就会,因为virtual是指向虚函数表的指针所以会继承基类中的存储空间。

#include <iostream>
using namespace std;
class A {
private:
	int a1;
public:
	virtual void func1() {}
	
};
class B : virtual public A {
private:
	int b;
public:
	virtual void func1() {}
	virtual void func2() {}
};
class C {


};
int main() {
	cout << "The size of class A is " << sizeof(A) << endl;
	cout << "The size of class B is " << sizeof(B) << endl;
	cout << "The size of class B is " << sizeof(C) << endl;
	
	
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值