Base类sizeof大小 -- C++

Base类只是一个指针,所以Base大小是4个字节。

但Base类中添加一个int a,Base的大小变成8字节。


#include <iostream>
#include <complex>

using namespace std;

class Base1
{
public:
	Base1(){cout << "Base1" << endl;}
	~Base1(){cout << "~Base1" << endl;}
	virtual void f(int){cout << "Base1 f(int)" << endl;}
	virtual void f(double){cout << "Base1 f(double)" << endl;}
	virtual void g(int i = 20){cout << "Base1 f(int)" << endl;}
	virtual void g2(int i = 10){cout << "Base1 f(int)" << endl;}
};

class Base2
{
public:
	Base2(){cout << "Base2" << endl;}
	~Base2(){cout << "~Base2" << endl;}
	virtual void f(int){cout << "Base2 f(int)" << endl;}
	virtual void f(double){cout << "Base2 f(double)" << endl;}
	virtual void g(int i = 20){cout << "Base2 f(int)" << endl;}
	virtual void g2(int i = 10){cout << "Base2 f(int)" << endl;}
	/* 4 字节 */
	int a;
};

class Base3
{
public:
	Base3(){ int a;int b;cout << "Base3" << endl;}
	~Base3(){cout << "~Base3" << endl;}
	virtual void f(int){cout << "Base3 f(int)" << endl;}
	virtual void f(double){cout << "Base3 f(double)" << endl;}
	virtual void g(int i = 20){cout << "Base3 f(int)" << endl;}
	virtual void g2(int i = 10){cout << "Base3 f(int)" << endl;}
	/* 4 字节 */
	int a;
	/* 4 字节 */
	int b;
};

int
main()
{
	Base1 a;
	/* 结果 4 字节 */
	cout << sizeof(Base1) << endl;

	Base2 b;
	/* 结果 8 字节 */
	cout << sizeof(Base2) << endl;
	
	Base3 c;
	/* 结果 12 字节 */
	cout << sizeof(Base3) << endl;

}
/*
[root@localhost test_class]# g++ class.cpp 
[root@localhost test_class]# ./a.out 
Base1
4
Base2
8
Base3
12
~Base3
~Base2
~Base1
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值