c++中类的大小和虚函数调用顺序

声明了一个父类一个子类。

class father
{
public:
	father();
	~father();
	virtual int getAge();
private:
	int m_age;
};

class child : public father
{
public:
	child();
	~child();
	virtual int getAge();
private:
	int m_age;
};


实现代码:

#include "test.h"
#include <iostream>
using namespace std;
father::father()
{
	cout<<"father() is Called"<<endl;
}
father::~father()
{
	cout<<" ~father() is Called "<<endl;
};
int father::getAge()
{
	m_age = 50;
	cout<< "father's getAge() is Called age = "<<m_age<<endl;
	return m_age;
}

child::child()
{
	cout<<" child() is Called "<<endl;
}
child::~child()
{
	cout<<" ~child() is Called"<<endl;

}
int child::getAge()
{	
	m_age = 20;
	cout<< "child's getAge() is Called age = "<<m_age<<endl;
	return m_age;
}

测试代码:

#include <iostream>
using namespace std;
#include "test.h"
int main()
{
	cout<<sizeof(father)<<endl;
	cout<<"父类的调用顺序"<<endl;
	father  * pfather = new father();
	cout<<sizeof(*pfather)<<endl;
	pfather->getAge();
	delete pfather;
	cout<<endl;
	cout<<sizeof(child)<<endl;
	cout<<"子类的调用顺序"<<endl;
	child  * pchild =new child();
	cout<<sizeof(*pchild)<<endl;
	pchild->getAge();
	delete pchild;
	return 0;
}


其中父类的成员变量m_age 占4字节,虚函数表指针占4字节 共有8字节。

子类在父类的基础上还要 ,增加自己的成员变量m_age。

测试结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值