C++ 重载和继承使用的分析

#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()
*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值