#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
class h2o
{
public:
virtual void hasH2o(void) = 0;
};
class person
{
public:
person();
virtual ~person();
virtual void eat();
void eat(int num);
};
person::person()
{
printf("person::person()\n");
}
person::~person()
{
printf("person::~person()\n");
}
void person::eat()
{
printf("person need eat\n");
}
void person::eat(int num)
{
printf("person + %d \n",num);
}
class man : public person ,virtual public h2o
{
public:
man();
virtual ~man();
virtual void eat();
void eat(int num);
virtual void hasH2o(void);
};
man::man()
{
printf("man::man()\n");
}
man::~man()
{
printf("man::~man()\n");
}
void man::eat()
{
printf("man eat meat\n");
}
void man::eat(int num)
{
printf("man + %d\n",num);
}
void man::hasH2o()
{
printf(" man has H2o \n");
}
/*
而重载方式的继承类被强转成基类再调用重载函数,则调用的是基类的函数。
*/
void printf_eat_int(person *p,int num)
{
p->eat(num);//void eat(int num);
man *m = reinterpret_cast<man*>(p);//将 base 类强制转换为子类
m->eat(num);
}
/*
使用虚函数继承时,当继承类被强转成基类后调用虚函数,调用的还是继承类的虚函数。
*/
void printf_eat(person *p)
{
p->eat();//virtual void eat();
man *m = reinterpret_cast<man*>(p);//将 base 类强制转换为子类
m->eat();
}
void hasH2o(h2o *p)
{
p->hasH2o();
/*
man *m = reinterpret_cast<man *>(p);//纯虚函数可以转换,但是执行crash
m->eat();
*/
}
int main(void)
{
man *m = new man();
printf_eat_int(m,4);
printf_eat(m);
hasH2o(m);
delete(m);
}
/*
$ ./virtual
person::person()
man::man()
person + 4
man + 4
man eat meat
man eat meat
man has H2o
man::~man()
person::~person()
*/