声明了一个父类一个子类。
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。
测试结果: